Click here to Skip to main content
15,890,282 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi guys.. im having a problem here on adding items to a combo box.. for example i have a database.. i have which has a sample field of firstname,lastname.. now.. here's the problem.. i dont know how to get just the lastname field for an example.. here's my code..

C#
string query = "select * from customer_tab";
MySqlCommand cmd;

cmd = new MySqlCommand(query, conn);

MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable table = new DataTable("myTable");
da.Fill(table);

foreach (DataRow row in table.Rows)
{
     for (int i = 0; i < row.ItemArray.Length; i++)
     {
          comboBox1.Items.Add(row.ItemArray[1].ToString());

     }
}
Posted
Updated 31-May-13 4:30am
v2
Comments
[no name] 31-May-13 10:08am    
If all you want is the last name then why are you not just querying your database for the last name?
ZurdoDev 31-May-13 10:30am    
We don't know where it is either because we can't see your database. Is the last name in the customer_tab table?

I think I would change the query to return only the last name if that's all you need, then set the combo box's DataSource to the query results rather than manually filling it.
 
Share this answer
 
Comments
lalar18 31-May-13 18:27pm    
thanks for the code but still im having a problem when loading the code.. i have already changed the code.. the error says that "Complex DataBinding accepts as a data source either an IList or an IListSource.",thanks in advance..:)
Marc A. Brown 31-May-13 19:04pm    
Try casting the DataSource to IListSource and calling the GetList() method. See also solution 2, which gives you some code.
C#
//Change query to be a little more specific
 //=====================================================================
 string query = "select first_name from customer_tab";
 MySqlCommand cmd;
 
 cmd = new MySqlCommand(query, conn);
 
 MySqlDataAdapter da = new MySqlDataAdapter(cmd);
 DataTable table = new DataTable("myTable");
 da.Fill(table);
 
 
 //Use this
 //=====================================================================
 comboBox1.DataSource = da;
 comboBox1.DisplayMember = "first_name";
 //=====================================================================
 
 
 
 //Forget all of this
 //=====================================================================
 //foreach (DataRow row in table.Rows)
 //{
 //     for (int i = 0; i < row.ItemArray.Length; i++)
 //     {
 //          comboBox1.Items.Add(row.ItemArray[1].ToString());
 //
 //     }
 //}
 //=====================================================================
 
Share this answer
 
v2

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