如何获取存储在组合框中显示的数据库中的数据
问题描述:
我正在使用C#.NET和SQL SERVER 2008制作窗口应用程序.我希望将存储在SQL SERVER中的数据显示在组合框上.我尝试了以下代码,但未能成功.
I am making window application using C#.NET and SQL SERVER 2008.I want that thedata which is stored in SQL SERVER get displayed on combobox.I tried following code but couldnt make it.
private void cbomedia_MouseClick(object sender, MouseEventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=SW-PC-20;Integrated security =SSPI;Initial catalog=PSM");
con.Open();
SqlCommand com = new SqlCommand("select * from Target_Audience", con);
SqlDataReader reader;
reader = com.ExecuteReader();
cbomedia.DataSource = reader;
cbomedia.DisplayMember = "Media_method_ID";
reader.Close();
con.Close();
}
我有一个错误
i got an error
complex DataBining accepts as a data source either an IList or an IListSource
请告诉我
问候
shivani
Please tell me
regards
shivani
答
尝试使用数据集
try it with Dataset
Dataset ds = new Dataset();
DataAdapter dt = new dataAdapter(Com);
dt.fill(ds);
comboBox2.DataSource = ds;
comboBox2.DisplayMember = "MemberName";
comboBox2.ValueMember = "MemID";
//with DataReader
try
{
// opening the connection
connection.Open();
OleDbDataReader dr = command.ExecuteReader();
if (dr.HasRows)
{
// Iterate through the table
while (dr.Read())
{
//adding item to the combobox. you can also use dr[1] to get the country name
comboBox1.Items.Add(dr["CountryName"]);
}
}
}
catch (Exception ex)
{
MessageBox.Show("The following error occured :rn" + ex.ToString());
}
finally
{
// close the connection and DataReader
connection.Close();
dr.Close();
}
}
请使用DataSet而不是SqlDataReader.
有关更多详细信息,请阅读本文
带有组合框的数据集
问候
AR
Hi,
Please use DataSet instead of SqlDataReader.
for More details go through with this article
DataSet with combobox
Regards
AR