How do I populate a listbox c # mysql

0

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();
    
asked by anonymous 06.01.2018 / 19:38

1 answer

0

You can use the DisplayMember property of ListBox to choose what to display.

1. Create a class

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; };
}

2. Create the ListBox

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.

3. Accessing data from the selected item

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

    
08.01.2018 / 13:00