Shiva Debrown
Shiva Debrown

Reputation: 177

How to set combobox value to null or empty while loading data to it from database in c#.net

I have a windows form coded in c#.. the problem is I have a combobox which is loaded values from database,and that code has written in LOAD form..

so,my form's combobox values are generated automatically to it and the Initial combobx text is loaded to it..

I want to set combobox initial text or value should be empty or null.. please help me to solve it.. Thanx in advance my code is as follows

 try
       {
           ConnectionStringSettings consettings = ConfigurationManager.ConnectionStrings["attendancemanagement"];
           string connectionString = consettings.ConnectionString;
           SqlConnection cn = new SqlConnection(connectionString);
           cn.Open();
           SqlCommand cmd = new SqlCommand("select employee_id,employee_name,image from Employee_Details", cn);
           SqlDataReader dtr;
           dtr = cmd.ExecuteReader();
           DataTable dt = new DataTable();
           dt.Columns.Add("employee_id", typeof(string));
           dt.Columns.Add("employee_name", typeof(string));
           dt.Load(dtr);
           //Convert.ToString.comboBox1.Items.Insert("", 0);
           comboBox1.DisplayMember = "employee_id";
           comboBox1.DisplayMember = "employee_name";
           comboBox1.DataSource = dt;
           //dateTimePicker1.Enabled = true; ;
           cn.Close();
       }

       catch (Exception e1)
       {
           MessageBox.Show(e1.Message);

       }

Upvotes: 2

Views: 15874

Answers (2)

Abdul Qayyum
Abdul Qayyum

Reputation: 1052

do not make it null, better to writer it Select as selected value.

           `dt.Load(dtr);
            DataRow drow = dt.NewRow();
            drow[0] = "-1";
            drow[1] = "Select";
            drow[2] = string.Empty;
            dt.Rows.InsertAt(drow, 0);
            dt.AcceptChanges();
            comboBox1.DisplayMember = "employee_id";
            comboBox1.DisplayMember = "employee_name";
            comboBox1.DataSource = dt;`

Upvotes: 0

Ghasem
Ghasem

Reputation: 15573

Add this line after you set your datasource to db:

comboBox1.SelectedItem = null;

Or

comboBox1.SelectedItem = -1;

Upvotes: 7

Related Questions