Cant read a simple listBox Text/Number [duplicate] - c#

I am trying to get the value of the selected item in the listbox using the code below, but it is always returning null string.
DataSet ds = searchforPrice(Convert.ToString(listBox1.SelectedItem));
Here I am trying to pass the value of selected item as string to method searchforPrice to retrive dataset from the database.
How can i retrive the value of selected item as string?
I am adding items to listbox from combo box which in turn loads the items from the database.
listBox1.Items.Add(comboBox2.Text);
Anybody has answer for this..

If you want to retrieve the display text of the item, use the GetItemText method:
string text = listBox1.GetItemText(listBox1.SelectedItem);

If you are using ListBox in your application and you want to return the selected value of ListBox and display it in a Label or any thing else then use this code, it will help you
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
label1.Text = listBox1.SelectedItem.ToString();
}

To retreive the value of all selected item in à listbox you can cast selected item in DataRowView and then select column where your data is:
foreach(object element in listbox.SelectedItems) {
DataRowView row = (DataRowView)element;
MessageBox.Show(row[0]);
}

string textValue = ((ListBoxItem)listBox1.SelectedItem).Content.ToString();

If you want to retrieve your value from an list box
you should try this:
String itemSelected = numberListBox.GetItemText(numberListBox.SelectedItem);

Get FullName in ListBox of files (full path) list (Thomas Levesque answer modificaton, thanks Thomas):
...
string tmpStr = "";
foreach (var item in listBoxFiles.SelectedItems)
{
tmpStr += listBoxFiles.GetItemText(item) + "\n";
}
MessageBox.Show(tmpStr);
...

You can Use This One To get the selected ListItme Name ::
String selectedItem = ((ListBoxItem)ListBox.SelectedItem).Name.ToString();
Make sure that Your each ListBoxItem have a Name property

Elaborating on previous answer by Pir Fahim, he's right but i'm using selectedItem.Text (only way to make it work to me)
Use the SelectedIndexChanged() event to store the data somewhere.
In my case, i usually fill a custom class, something like:
class myItem {
string name {get; set;}
string price {get; set;}
string desc {get; set;}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
myItem selected_item = new myItem();
selected_item.name = listBox1.SelectedItem.Text;
Retrieve (selected_item.name);
}
And then you can retrieve the rest of data from a List of "myItems"..
myItem Retrieve (string wanted_item) {
foreach (myItem item in my_items_list) {
if (item.name == wanted_item) {
// This is the selected item
return item;
}
}
return null;
}

set properties listbox1 DisplayMember = "Text";
set properties listbox1 ValueMember = "Value";
Event
private void listbox1_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedValue = listbox1.SelectedValue.ToString();
}

The correct solution seems to be:
string text = ((ListBoxItem)ListBox1.SelectedItem).Content.ToString();
Please be sure to use .Content and not .Name.

If you want to retrieve the item selected from listbox, here is the code...
String SelectedItem = listBox1.SelectedItem.Value;

Related

How to get listbox selected item value

I am working with C# .NET 4.0
I am trying to get the value of a single selected item in a listbox.
This is how I populate the control:
this.files_lb.DataSource = DataTable object
In my designer, I have specified file_name as the DisplayMember and file_id as the DisplayValue
After selecting an item in the listbox, I tried the following to get the value:
this.files_lb.SelectedValue.ToString()
But all it returns is "System.Data.DataRowView".
At this link : Getting value of selected item in list box as string
someone suggested -
String SelectedItem = listBox1.SelectedItem.Value
However, 'Value' is not an option when I try this.
How can I get the ValueMember value from a single selected item in a listbox?
var text = (listBox1.SelectedItem as DataRowView)["columnName"].ToString();
Replace columnName with the name of the column you want to get data from, which will correspond with a column in your datasource.
Also watch out for nulls if there's no selected item.
It really should be this easy; I have the following in a click event for button to make sure I wasn't over simplifying it in my head:
private void button1_Click(object sender, EventArgs e)
{
string selected = listBox1.GetItemText(listBox1.SelectedValue);
MessageBox.Show(selected);
}
And the result:
Edit
It looks like your issue may be from not setting a property on the control:
Select the ListBox control
Click the little arrow to show the binding / items options
Select Use Data Bound Items
If I deselect that box, I get the exact same behavior you are describing.
var selectedValue = listBoxTopics.SelectedItem;
if (selectedValue != null)
{
MessageBox.Show(listBoxTopics.SelectedValue.ToString());
}
You may need to set the DataValueField of the listbox.
NewEmployeesLB.DataSource = newEmployeesPersons.DataList.Select(np => new
ListItem() { Text = np.LastName + ", " + np.FirstName, Value = np.PersonID.ToString() }).ToList();
NewEmployeesLB.DataTextField = "Text";
NewEmployeesLB.DataValueField = "Value";
NewEmployeesLB.DataBind();

how should I give the user a selection and grab the guid from that selection

I have to give the user an option to select from a list of items and then, pending on what single item they select, I need to get the guid from that item. This will be populated from a Linq query from a Sql table.
I started with this:
private void PopulateGatewayList()
{
var gateways = from gw in _entities.Gateways
where gw.IsActive
select gw;
foreach (var gateway in gateways)
{
checkedListBox_Gateways.Items.Add(gateway.Name);
}
}
But I have no way of grabbing the guid once they check something.
What is a good way of giving the user the name but give me back the guid?
** ANSWER **
Using Michael Yoon's help, I did the following:
private void PopulateGatewayList()
{
var gateways = from gw in _entities.Gateways
where gw.IsActive
select gw;
foreach (var gateway in gateways)
{
checkedListBox_Gateways.Items.Add(new ListItem(gateway.Name, gateway.GatewayId.ToString()));
//checkedListBox_Gateways.Items.Add(gateway.Name);
}
}
private void checkedListBox_Gateways_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (Object selecteditem in checkedListBox_Gateways.SelectedItems)
{
var strItem = selecteditem as ListItem;
Console.WriteLine("Selected: " + strItem.Value);
}
}
You need to add an object to the collection that contains the id and string. You can use KeyValuePair or make your own. I'll use keyvaluepair in my example.
checkedListBox_Gateways.DisplayMember = "Key";
checkedListBox_Gateways.ValueMember = "Value";
checkedListBox_Gateways.Items.Add(new KeyValuePair<string, string>(gateway.Name, gateway.Id.ToString()));
Then you can enumerate the SelectedItems collection, cast each back to a keyvaluepair and get the value out of it.

Getting value of selected item in list box as string

I am trying to get the value of the selected item in the listbox using the code below, but it is always returning null string.
DataSet ds = searchforPrice(Convert.ToString(listBox1.SelectedItem));
Here I am trying to pass the value of selected item as string to method searchforPrice to retrive dataset from the database.
How can i retrive the value of selected item as string?
I am adding items to listbox from combo box which in turn loads the items from the database.
listBox1.Items.Add(comboBox2.Text);
Anybody has answer for this..
If you want to retrieve the display text of the item, use the GetItemText method:
string text = listBox1.GetItemText(listBox1.SelectedItem);
If you are using ListBox in your application and you want to return the selected value of ListBox and display it in a Label or any thing else then use this code, it will help you
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
label1.Text = listBox1.SelectedItem.ToString();
}
To retreive the value of all selected item in à listbox you can cast selected item in DataRowView and then select column where your data is:
foreach(object element in listbox.SelectedItems) {
DataRowView row = (DataRowView)element;
MessageBox.Show(row[0]);
}
string textValue = ((ListBoxItem)listBox1.SelectedItem).Content.ToString();
If you want to retrieve your value from an list box
you should try this:
String itemSelected = numberListBox.GetItemText(numberListBox.SelectedItem);
Get FullName in ListBox of files (full path) list (Thomas Levesque answer modificaton, thanks Thomas):
...
string tmpStr = "";
foreach (var item in listBoxFiles.SelectedItems)
{
tmpStr += listBoxFiles.GetItemText(item) + "\n";
}
MessageBox.Show(tmpStr);
...
You can Use This One To get the selected ListItme Name ::
String selectedItem = ((ListBoxItem)ListBox.SelectedItem).Name.ToString();
Make sure that Your each ListBoxItem have a Name property
Elaborating on previous answer by Pir Fahim, he's right but i'm using selectedItem.Text (only way to make it work to me)
Use the SelectedIndexChanged() event to store the data somewhere.
In my case, i usually fill a custom class, something like:
class myItem {
string name {get; set;}
string price {get; set;}
string desc {get; set;}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
myItem selected_item = new myItem();
selected_item.name = listBox1.SelectedItem.Text;
Retrieve (selected_item.name);
}
And then you can retrieve the rest of data from a List of "myItems"..
myItem Retrieve (string wanted_item) {
foreach (myItem item in my_items_list) {
if (item.name == wanted_item) {
// This is the selected item
return item;
}
}
return null;
}
set properties listbox1 DisplayMember = "Text";
set properties listbox1 ValueMember = "Value";
Event
private void listbox1_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedValue = listbox1.SelectedValue.ToString();
}
The correct solution seems to be:
string text = ((ListBoxItem)ListBox1.SelectedItem).Content.ToString();
Please be sure to use .Content and not .Name.
If you want to retrieve the item selected from listbox, here is the code...
String SelectedItem = listBox1.SelectedItem.Value;

Using Lists With Textboxes

This is my code for adding to my list:
List<string> myList = new List<string>();
private void button1_Click(object sender, EventArgs e)
{
ListViewItem myList = new ListViewItem(txtBox1.Text);
myList.SubItems.Add(txtBox2.Text);
myList.SubItems.Add(txtBox3.Text);
myList.SubItems.Add(txtBox4.Text);
listView1.Items.Add(myList);
txtBox1.Text = "";
txtBox2.Text = "";
txtBox3.Text = "";
txtBox4.Text = "";
}
This adds to my list and clears and lets me add another post to my list. The problem is I want to be able to repopulate the textboxes to allow me to update a post in the list.
To make my point more clear, my list looks like this:
Code | Name | Price | In stock
------------------------------
123 aa 122 2
124 bb 111 5
Say I want the first post, can I somehow set all the data back into the textboxes by that identifier or do I have search by index? I would like to be able to put the code in the first textbox then hit a button called retrieve that populates the other textfield kinda like going by the unique key in an sql table but I cant find any info on wether its possible or not.
Why don't you create a class that has Code, Name, Price, In stock, and use a List
Public MyItem
{
public string Code;
public string Name,
public float Price;
public bool inStock;
}
List<MyItem> myList = new List<MyItem>();
private void button1_Click(object sender, EventArgs e)
{
MyItem temp = new MyItem()
temp.Code=txtBox1.Text;
temp.Name=(txtBox2.Text);
temp.Price=(txtBox3.Text);
temp.inStock=(txtBox4.Text);
mylist.add(temp);
txtBox1.Text = "";
txtBox2.Text = "";
txtBox3.Text = "";
txtBox4.Text = "";
}
If you implement it this way then you can just use the index to go through all the items in the list. With the example above you would probably need to convert some of the values from the text boxes before you can use them (price to double)
Also if you want to add the items to a Listview and display them a certain way then override the toString property in the MyItem class and you can display whatever text you want. Hope this helps.
You shouldn't store data only in controls. I would create a class to hold all the info about a particular item, and populate THAT with the contents of the textboxes, and store it in some collection (Maybe a dictionary if you want to look one up by code)
You can then add a reference to this object in the "Tag" property of ListViewItem, so you can immediately grab it from any selected ListViewItem.
I dont quite understand what you mean by saying "can I somehow set all the data back into the textboxes by (that identifier) " which identifier ?!
but i would get data like this:
var item = listview1.items.where(x=>x.SubItems[0].value == mycodeId).firstordefault();
now i have the item i can retrieve data from it:
textbox1.Text = item[1].value;

Copy items from ListBox to CheckedListBox

There are many questions that ask the opposite of this question, unfortunately none of them have worked for me. I have the following code to achieve my purpose:
foreach (var item in listBox1.Items)
{
checkedListBox1.Items.Add(item);
}
The problem is that when I do this, I don't get the values inside the ListBox, rather the System.Data.DataRowView items. So my CheckedListBox gets populated with exactly this, System.Data.DataRowView strings, which are all the same and don't show the actual string value.
Edit: I bind to the ListView this way: I have a DataTable ds, and:
listBox1.DataSource = ds;
For some unknown reason, DataSource, DisplayMember and ValueMember properties are hidden for CheckedListBox control.
If you want to copy the the list box items text, the correct way is to use ListControl.GetItemText method like this
foreach (var item in listBox1.Items)
checkedListBox1.Items.Add(listBox1.GetItemText(item));
But this way it will be hard to find which source object is checked (for instance when enumerating CheckedItems). A better way would be to define your own class like this
class MyListItem
{
public object Value;
public string Text;
public override string ToString() { return Text; }
}
and use
foreach (var item in listBox1.Items)
checkedListBox1.Items.Add(new MyListItem { Value = item, Text = listBox1.GetItemText(item) });
Try this:
foreach (var dataRowView in listBox1.Items.OfType<DataRowView>())
{
checkedListBox1.Items.Add(dataRowView[0].ToString());
}
The text displayed by derived ListControl classes like a CheckedListBox, when these controls are binded to a datasource, is ruled by the property DisplayMember. This property equals to a string representing the name of a property (or a columnname) in the datasource.
So before adding the new items to your checkedlistbox I suggest to write
checkedListBox1.DataSource = listBox1.DataSource
checkedListBox1.DisplayMember = listBox1.DisplayMember
checkedListBox1.ValueMember = listBox1.ValueMember
And no need to create a loop reading all the items from the source listbox, just use the same datasource and your are ready
You need to do a cast like the following :
foreach (var item in listBox1.Items)
{
checkedListBox1.Items.Add((ListItem)item);
}
or else you can use like this:
foreach (ListItem item in listBox1.Items)
{
checkedListBox1.Items.Add(item);
}
even this also may help you(use like this if you want text and value);
for(int i=0;i<listBox1.Items.Count-1;i++)
{
checkedListBox1.Items.Add(new ListItem() { Text = listBox1.Items[i].Text, Value = listBox1.Items[i].Text });
}

Categories