Adding Values to ComboBox dropdown list from database CSharp(C#)

ComboBox Control in C Sharp

Combobox is a editable DropDownBox.DropDownBox is a ASP.Net controler but here in the C#
combobox will works as a dropdownbox.Adding values to the ComboBox dropdown list from the database is a simple process.Basically ComboBox will have three dropDown styles.Those styles will make the ComboBox three different styles. Those are Simple,DropDown and DropDownList.If you select the Simple DropDownStyle the combobox will appear as a textbox.Another one is DropDown, in this DropDownStyle the combobox will able to take the text from the user and the shows the drodown of perticulars those contain in DataBase.And the DropDown list property will not allow the user to enter the
new value. User must selectthe values from dropdown list only. If you want to check textbox alidations   please click here.The DropDownStyle you have to set is DropDown when you have to enter the text from the user or if you don't need to allow the user to enter a new value means you must set DropDownList proprty from droopdownstyles. Click here for ComboBox tutorials.

Event: This code should write in Form_Load event.

SqlConnection con = new SqlConnection(@"Data Source=CENSYS10\SQLEXPRESS;Integrated Security=true;Initial Catalog=master");
con.Open();

da = new SqlDataAdapter("select * from DbTable", cn);
da.Fill(ds);

comboBox1.DataSource = ds.Tables[0];
comboBox1.DisplayMember = "DbColumname";
comboBox1.ValueMember = "DbColumnname";
con.Close();

DbColumname is the column name in the database table.And the value member and display member
will be same column from database.

I hope this code will helps you.

No comments:

Post a Comment