how to fill combobox from database in c sharp/c#
  • hi i want fill combobox from database in c# any idea ?
  • 5 Comments sorted by
  • Vote Up1Vote Down WaqasWaqas
    172.00 Karma Accepted Answer
    Hi use the following code.

    SqlConnection objCon = new SqlConnection(@"Data Source=.\SqlExpress;Initial Catalog=YourDatabaseName;Integrated Security=True");

                SqlCommand objCmd = new SqlCommand("select Column1,Column2 from TableName", objCon);

                SqlDataAdapter objDA = new SqlDataAdapter(objCmd);

                objDA.SelectCommand.CommandText = objCmd.CommandText.ToString();
                DataTable dt = new DataTable();

                objDA.Fill(dt);
                comboBox1.DataSource = dt;

        //this column1 will display as text
                comboBox1.DisplayMember = "Column1";    

        //this column2 will use as back end value who can you use in selectedValue property
                comboBox1.ValueMember = "Column2";       
  • Waqas thanks for sharing this Code..

    Thanks again
  • Good work waqas.
  • At this I want to say all that always make a function to return datatable for any purpos
    in a class like this

    public datatable mydt(sqlstring)
    {
    SqlConnection objCon = new SqlConnection(@"Data Source=.\SqlExpress;Initial Catalog=YourDatabaseName;Integrated Security=True");

                SqlCommand objCmd = new SqlCommand("select Column1,Column2 from TableName", objCon);

                SqlDataAdapter objDA = new SqlDataAdapter(objCmd);

                objDA.SelectCommand.CommandText = objCmd.CommandText.ToString();
                DataTable dt = new DataTable();

                objDA.Fill(dt);

    return dt;

    }
    and at any query/procedures you can get datatable like below

    datatable abc=new datatable();
    string mysqlstr="select * from tblname";
    //or any query
    abc=classobjname.mydt(mysqlstr);
    //if you want to fill dropdown then
    give datasource ,textfeildname,valuefeildname like above in waqas solution
  • In this part of code:
    datatable abc=new datatable();
    string mysqlstr="select * from tblname";
    //or any query
    abc=classobjname.mydt(mysqlstr);
    it's better do this:
    string mysqlstr="select * from tblname";
    //or any query
    Datatable abc=classobjname.mydt(mysqlstr);
    In the first case you initialize an object than never uses.


Howdy, Stranger!

It looks like you're new here. If you want to get involved, or you want to Ask a new Question, Please Login or Create a new Account by Clicking below

Login with Facebook

Tagged

Popular Posts of the Week

    Optimum Creative