How do I populate a ListBox with C # and mysql and at the same time put the value of each record?
So far I've been able to set up the name but not the code for each one:
Mat_sel.Items.Add(reader["mat_nome"]).ToString();
How do I populate a ListBox with C # and mysql and at the same time put the value of each record?
So far I've been able to set up the name but not the code for each one:
Mat_sel.Items.Add(reader["mat_nome"]).ToString();
You can use the DisplayMember
property of ListBox
to choose what to display.
First, create a class that will serve as the object of your list. For example, a class named SomeData
, which will store the text and the value you will fetch from the database:
public class SomeData
{
public string Value { get; set; };
public string Text { get; set; };
}
Now, create your ListBox as follows (note that I used reader["mat_codigo"]).ToString()
because I do not know the name of the column of code that is in your database):
List<SomeData> data = new List<SomeData>();
data.Add(new SomeData() { Value = reader["mat_codigo"]).ToString(), Text = reader["mat_nome"]).ToString()});
data.Add(new SomeData() { Value = reader["mat_codigo"]).ToString(), Text = reader["mat_nome"]).ToString()});
listBox1.DisplayMember = "Text";
listBox1.DataSource = data;
Where "Text"
listBox1.DisplayMember = "Text"
is the property name Text
of its SomeData
class.
When the user selects an item, you can read the value (or any other property) of the selected object:
string value = (listBox1.SelectedItem as SomeData).Value;
string text = (listBox1.SelectedItem as SomeData).Text;
Translated and adapted from: Make ListBox items have a different value than item text