How do I fill a listbox c# mysql

Asked

Viewed 577 times

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();

1 answer

0


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

1. Create a class

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

2. Create the Listbox

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.

3. Accessing data from 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.