Thursday, August 27, 2009

how to set combobox value from database c#

To show combo box value from database . to do that i have used a test table student and colum id and naem

id is int data type and name is varchar data type .

after creating sql table and make a suitable conncetion then apply these code to show combobox value from database .




dbconnection dbconn = new dbconnection();

SqlDataReader rdr = null;

DataTable dt = new DataTable();

string sqlquery = "select * from student where status='1'";

try
{
dbconn.connection.Open();

SqlCommand cmd4 = new SqlCommand(sqlquery, dbconn.connection);



rdr = cmd4.ExecuteReader();

dt.Columns.Add("Id");

dt.Columns.Add("name");



while (rdr.Read())
{


int id = (int)rdr["id"];

string name= (string)rdr["name"];

string comboid = Convert.ToString(id);



dt.Rows.Add(id, name);

}


dt.AcceptChanges();



this.comboBox1.DisplayMember = "name";

this.comboBox1.ValueMember = "Id";

this.comboBox1.DataSource = dt;



if (rdr != null)
{
rdr.Close();
}

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




For this You need a combobox first take it from tools in your project tool bar .

No comments:

Post a Comment