Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I get "System.Data.DataRowView" instead of real values in my Listbox?

Tags:

c#

mysql

winforms

Whenever I run my code and try to view a highscore all I get back in my listbox is System.Data.DataRowView.

Can anyone see why?

Code:

MySqlConnection myConn = new MySqlConnection(connStr);
    
string sqlStr = "SELECT CONCAT(Name, ' ', Score) as NameAndScore " + 
                "FROM highscore ORDER BY Score DESC";
    
MySqlDataAdapter dAdapter = new MySqlDataAdapter(sqlStr, myConn);
DataTable dTable = new DataTable();
dAdapter.Fill(dTable);
dAdapter.Dispose();
lstNames.DisplayMember = "NameAndScore";
lstNames.DataSource = dTable;
like image 208
Cain Neal Avatar asked Mar 15 '13 09:03

Cain Neal


2 Answers

I always have to deal with this problem, even if I set the DisplayMember and ValueMembers of the List Box.

Your current code is correct and should work, if you need access to the current selected item value of any column of your dTable you can get them doing this:

DataRowView drv = (DataRowView)lstNames.SelectedItem;
String valueOfItem = drv["NameAndScore"].ToString();

What I like about getting the entire DataRowView is that if you have more columns you can still access their values and do whatever you need with them.

like image 97
echavez Avatar answered Oct 16 '22 10:10

echavez


The following code should work:

DataSet dSet = new DataSet();
dAdapter.Fill(dSet);

lstNames.DisplayMember = "NameAndScore";
lstNames.ValueMember = "NameAndScore";
lstNames.DataSource = dSet.Tables[0];

If it does not work, please update your question and provide us with some information about the columns and values that are actually returned in dSet.Tables[0].

like image 45
Thorsten Dittmar Avatar answered Oct 16 '22 09:10

Thorsten Dittmar