aHunter
aHunter

Reputation: 3530

c# populating and using the value from a combo box with MySQL in a Windows Form Application

I have a combo box in a C# Windows form application that is being populated from a mysql database query using the following code.

MySqlDataAdapter sqlquery = new MySqlDataAdapter("SELECT users.username AS username, users.Id AS id FROM users", conn);
DataTable populateDreturnCBox = new DataTable("users");
sqlquery.Fill(populateDreturnCBox);

dreturnCbox1.DataSource = populateDreturnCBox;
dreturnCbox1.ValueMember = populateDreturnCBox.Columns[1].ColumnName;
dreturnCbox1.DisplayMember = populateDreturnCBox.Columns[0].ColumnName;

This does appears to work but the issue is that when I pass the SelectedValue.ToString() into a string variable, as shown below, I get a string with System.Data.DataRowView displayed instead of the string value selected.

string val = dreturnCbox1.SelectedItem.ToString();
MessageBox.Show(val);

I realise that I am trying to access an array of data values but am not sure how to pass the value. Do I need to create a for loop to find the index position in order to access the data in the combo box, or am I barking up the wrong tree with this?

Thanks in advance.

Upvotes: 0

Views: 1042

Answers (1)

c0deNinja
c0deNinja

Reputation: 3986

how bout something like this:

string val = ((DataRowView)dreturnCbox1.SelectedItem).Row[1];

Upvotes: 1

Related Questions