Click here to Skip to main content
15,895,011 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi,

I wanna add 1 column data from datatable to listbox here is the code by which i am not able to achieve ..! here dt1 is a datatable.

C#
for (i = 0; i < dt1.Rows.Count; i++)
{
    ListBox1.Items[i].value = dt1.Rows[i][1].ToString();
}


thanks in advance.
Posted

Instead of adding the items yourself, simply use the DataSource DisplayMember and ValueMember, like this:

C#
listBox1.DataSource = dt1;
listBox1.DisplayMember = "Name";
listBox1.ValueMember = "ID";

Name and ID need to be replaced by columns in your table.


If you would like to see more columns, have a look here:
http://www.codeproject.com/KB/combobox/multicolumnlistbox.aspx[^]

Good luck!
 
Share this answer
 
v3
Comments
David Obinger 5-Jun-17 11:11am    
Thanks for the tip, but I have got another problem shortly thereafter:
Every time I select another item, the text of the previously selected item changes itself to a number, which is the ID of the currently selected item. When you select one of these numbers, it jumps to the item, which has the corresponding ID.
E.g. If I select the item "4" (which is actually #7 in the listBox index) it jumps to item #4 and changes item #4 to "7".
Got any clues what happened?
E.F. Nijboer 9-Jun-17 16:09pm    
No, sorry. Maybe post a new question here on codeproject with some code to help explain the problem.
Hi,
try this:

using (SqlConnection conn = new SqlConnection(CONN_STR))
using (SqlDataAdapter da = new sqlDataAdapter("roboticSiteNames", conn)) {
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];

// 1. set DisplayMember and ValueMember
lbSiteCode.DisplayMember = dt.Columns[0].ColumnName;
lbSiteCode.ValueMember = dt.Columns[1].ColumnName;
// 2. set DataSource
lbSiteCode.DataSource = dt;
}


Regards
Robert
 
Share this answer
 
v2
C#
List<string> lst = new List<string>();
           foreach (DataRow r in dt.Rows)
           {
               lst.Add(r["ColumnName"].ToString());
           }
           listBox1.Items.Clear();
           listBox1.DataSource = lst;
 
Share this answer
 
Comments
Henry Minute 15-Nov-10 11:53am    
Why disassociate the ListBox from the Data by having the unnecessary and time consuming task of creating a List<>?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900