Rookie
Rookie

Reputation: 113

combobox items from the database

In C# I used a combo box in my form and I wish to obtain a specific column from a table in the database and contents of the column to be added as the items in the combo box. I have declared this way

string strCon, strQry;
SqlConnection con;
SqlDataAdapter da;
DataSet ds;
SqlCommand comm;

den strcon= data source =" " initial catalog =" " use id =" " password=" ";
con = new sqlconnection(strcon);
strquery = select city from the cities;
da = new sqladapter(strqry,con);
ds = new dataset;
da.fill(ds, " cities");

Should I put for loop till items continue adding?

Update:

I want the entire column to be added as the items in the check box. On click of the check box, I want the entire column to be displayed as respective item in the check box.

Upvotes: 0

Views: 5260

Answers (2)

nashUWU
nashUWU

Reputation: 15

comboBox1.Items.Add(drCities.Cells[0].Value);
comboBox1.Items.Add(drCities.Cells[1].Value);

Upvotes: 1

Naeem Sarfraz
Naeem Sarfraz

Reputation: 7430

Try this: if you want to display one column called 'Name' then...

comboBox1.DataSource = ds;
comboBox1.DisplayMember = "Name";

else, as you have described, you might want to do this...

foreach(DataRow drCities in ds.Tables[0].Rows)
{
  string sValue = string.Format("{0} {1} {2}", drCity["Name"], drCity["Col1"], drCity["Col2"]);
  comboBox1.Items.Add(sValue);
}

the above code would sit in the Form load event which is usually...

private void Form1_Load(object sender, EventArgs e)
{
  ....
}

Upvotes: 0

Related Questions