Click here to Skip to main content
15,885,985 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
please help me... i want fill ComboBox from database sql server and i use this code below but can't works..
C#
protected void FillComboBox()
    {

            SqlDataAdapter da = new SqlDataAdapter("SELECT ItemName FROM TBItemList", oSqlConn);
            DataTable dt = new DataTable();
            da.Fill(dt);
            {
                cbxparameter.Items.Add(dt.ToString());
            }

    }


then to make sure my code, i'm try to bug and in my bug i'm can't know where the trouble.. because all normal, Why ?
Posted
Updated 28-Jun-21 21:13pm

set the data source as your data table and then you can specify the column which you want to display and the value of the item as below
C#
SqlDataAdapter da = new SqlDataAdapter("SELECT ItemName FROM TBItemList", oSqlConn);
DataTable dt = new DataTable();
da.Fill(dt);
cbxparameter.DataSource=dt;
cbxparameter.DisplayMember="ItemName";
cbxparameter.ValueMember="ItemName";
 
Share this answer
 
You can fill combo box in two ways.. either by using the datasource property or by using the for loop to fill.

1st Way - Data source Property

C#
SqlDataAdapter da = new SqlDataAdapter("SELECT ItemName FROM TBItemList", oSqlConn);
DataTable dt = new DataTable();
da.Fill(dt);
cbxparameter.DataSource=dt; // setting the datasource property of combobox
cbxparameter.DisplayMember="ItemName"; // Display Member which will display on screen
cbxparameter.ValueMember="ItemID"; //ID Member using which you will get the selected Item ID 


2nd Way - For Loop
C#
SqlDataAdapter da = new SqlDataAdapter("SELECT ItemName FROM TBItemList", oSqlConn);
DataTable dt = new DataTable();
da.Fill(dt);
for(int i=0;i<dt.rows.count;i++)
{
    cbxparameter.Items.Add(dt.rows[i]["ItemName"].toString());
}
 
Share this answer
 
v2
Comments
Member 11057420 14-Jan-15 23:20pm    
@jeet Gupta, thx before to your respon,

actualy, i'm has been use 2way it, but still can't work, i don't know what happened with my code, then i'm try to bug my code and then i'm check value oSqlConn and result noproblem, then i'm check (dt) and result all list show. which i don't know why from combobox canot show...
and im try to create new project it's work but in my old project still can't work

Any idea?
Jeet Gupta 16-Jan-15 1:56am    
just post the code which you are using then i can check is there any problem in the code or not.

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