0
How do I fill a Listbox with C# and mysql and at the same time put the value of each record?
until the moment I managed to configure to appear the name, but not the code of each:
Mat_sel.Items.Add(reader["mat_nome"]).ToString();
0
How do I fill a Listbox with C# and mysql and at the same time put the value of each record?
until the moment I managed to configure to appear the name, but not the code of each:
Mat_sel.Items.Add(reader["mat_nome"]).ToString();
0
You can use the property DisplayMember
of ListBox
to choose what to show.
First, create a class that will serve as the object of your list. For example, a class called SomeData
, which will store the text and the value you seek 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 don’t know the name of the column of the code that’s 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 the "Text"
of listBox1.DisplayMember = "Text"
is the name of the property Text
of your class SomeData
.
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
Thank you very much, it helped a lot.
Browser other questions tagged c# mysql
You are not signed in. Login or sign up in order to post.
What is the type of the Mat_sel object and what is the name of the value column you want to add?
– Leandro Angelo
Possible duplicate of How to give a select to only get some mysql record
– Daniel Alencar Souza