tags:

views:

96

answers:

4

I want to store once Column data of Table in combobox1? Here is the code that isn't working:

SqlCommand cmdRe = new SqlCommand("select FK_RoleID from SO_User_Table", cn);
        SqlDataAdapter da = new SqlDataAdapter();
        DataTable dt = new DataTable();
        try
        {
            cn.Open();
            da.SelectCommand = cmdRe;
            da.Fill(dt);
             // textBox1.Text = dt.Rows[0].ItemArray[0].ToString();

          this.comboBox1.DisplayMember= "FK_RoleID";
          this.comboBox1.ValueMember = "FK_RoleID";
          this.comboBox1.DataSource = da;
        }

        catch (System.Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {

            cn.Close();
        }
A: 

Call DataBind() on your comboBox1 control:

this.comboBox1.DataSource = da;
this.comboBox1.DataBind();
roosteronacid
+4  A: 

You need to bind to the table, not the adapter:

this.comboBox1.DataSource = dt;

Also - if you use using, you can simplify the code a bit (you don't need the finally etc):

using(SqlCommand cmdRe = {blah}) {
    // {blah}
}

As a final point - as you progress with .NET development, you may want to think about separating your UI and data logic. Talking to a db-command and ui-control in the same method (or even dll) is often a code-smell.

Marc Gravell
A: 

Looking very quickly, you should be using the dt as the datasource, not the dataadapter. Second, there is no need for the sqlcommand object if you are using the dataadapter and C# 2.0 or 3.0, place the select statement in the constructor of the dataadapter (MSDN link - http://msdn.microsoft.com/en-us/library/bh8kx08z.aspx). Hope that helps.

Wade

Wade73
+1  A: 

You have to set the DataValueField and DataTextField properties of the combobox. Check the modifications below.

void textbox_value_load()
        {
            SqlCommand cmdRe = new SqlCommand("select FK_RoleID from SO_User_Table", cn);
            SqlDataAdapter da = new SqlDataAdapter();
            DataTable dt = new DataTable();
            try
            {
                cn.Open();
                da.SelectCommand = cmdRe;
                da.Fill(dt);


                this.comboBox1.DataSource = da;
                this.comboBox1.DataValueField = ""; //Name of the Id column
                this.comboBox1.DataTextField = ""; //Name of the value/name column
                this.comboBox1.DataBind();


            }

            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {

                cn.Close();
            }

        }
Colour Blend
You, ah, missed the .ComboBox1 part of those two added lines. =)
J. Steen
Oh! sorry. Thanks for noting dat.
Colour Blend