Link ComboBox With Database in Window Form

Here I will explain how to Link a combobox with a database. Before this I explain how to use a combobox.

Step(1): Form with ComboBox

Drag and drop a combobox from the Toolbox.

Step(2): Coding

Now in the coding section make a function connected to the database and call this method in the constructor.


Void fillcombo()
{
string str = "server = MUNESH\\SQL2008R2;Database=datastore;UID=sa;Password=123;";
SqlConnection con = new SqlConnection(str);
string query = "select * from tablename";
SqlCommand cmd = new SqlCommand( query,con);
sqldatareader dbr;
try
{
con.open();
dbr = cmd.executereader();
while(dbr.read())
{
string sname = (string) myreader["name"];; //name is coming from database
combobox1.items.Add(sname);
}
catch(execption es)
{
messagebox.show(es.message);
}
}
}

Step(3): Output

When you run your application the data (we are fetching the name from the database) is to be stored in the combobox.

 
You can also go to my blog_munesh .


Similar Articles