Answered by:
Populate list box

Question
-
Please suggest what property should i use to populate List Box with distinct department ID's.
private void fillListBox() { try { SqlConnection conn = new SqlConnection("Data Source='User-PC';Initial Catalog='mm';User Id='sa';Password='El1f0rt3m'"); SqlCommand cmd = new SqlCommand("select distinct(Department) from box where code = "+textBox1.Text+""); cmd.CommandType = CommandType.Text; DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(); cmd.Connection = conn; da.SelectCommand = cmd; da.Fill(ds); checkedListBox1.Items.Add(ds.Tables[0]); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
Friday, September 17, 2010 4:35 PM
Answers
-
Another way to populate is to bind your dataSet with listBox:
This is for your case, when you have only 1 column in ds.listBox1.DataSource = ds.Tables[0]; listBox1.DisplayMember = dt.Columns[0].ColumnName; //here comes an id listBox1.ValueMember = dt.Columns[0].ColumnName; //here comes what is dispalyed!
- Marked as answer by Haris Hussain Friday, September 17, 2010 5:26 PM
Friday, September 17, 2010 4:51 PM
All replies
-
Are you sure that your SQL query is correct? The "from box where code = "+textBox1.Text+" part makes me think that you are not accessing a database. In any case, since you are using SELECT DISTINCT it should insure that the results you are getting are distinct even before you are populating the List Box.
In general, one way to ensure that your ListBox contains only distinct values would be by calling its Contains method on every object you want to add and adding it only if the method returns false.
Another thing, for your safety, I would suggest removing username/password information from your question.
- Edited by GonzoKnight Friday, September 17, 2010 4:46 PM
Friday, September 17, 2010 4:43 PM -
foreach(DataRow dr in ds.Tables[0].Rows) { listBox.Items.Add(dr[0].ToString()); }
... if you have values in dataSet to populate listBox.
But if you have only one type of data, you dont need to use dataSet. You can easily use DataTable (dataSet can consists of multiple dataTables).Then you populate: foreach(DataRow dr in myDataTable.Rows){}- Proposed as answer by GonzoKnight Friday, September 17, 2010 4:48 PM
Friday, September 17, 2010 4:45 PM -
The query is correct and dataset holds distinct department ID's.Friday, September 17, 2010 4:47 PM
-
Another way to populate is to bind your dataSet with listBox:
This is for your case, when you have only 1 column in ds.listBox1.DataSource = ds.Tables[0]; listBox1.DisplayMember = dt.Columns[0].ColumnName; //here comes an id listBox1.ValueMember = dt.Columns[0].ColumnName; //here comes what is dispalyed!
- Marked as answer by Haris Hussain Friday, September 17, 2010 5:26 PM
Friday, September 17, 2010 4:51 PM