我使用了DataRow,它可以在我的WinForm中的组合框中显示但不知何故,它不起作用,尽管整个表格已成功显示在gridview中。
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
con.ConnectionString = "Data Source=.;Initial Catalog=StudentDetails;Integrated Security=True";
cmd.Connection = con;
cmd.CommandText = "select * from StuDet";
da.SelectCommand = cmd;
da.Fill(ds);
dt = ds.Tables[0];
dataGridView1.DataSource = dt;
DataRow dr = dt.NewRow();
for (int i = 0; i < dt.Rows.Count; i++)
{
comboBox1.Items.Add(dr[0]);
}
}
答案 0 :(得分:2)
您创建一个空的新行
DataRow dr = dt.NewRow();
并将其Rows.Count
次添加到comboBox1
。我想你想要的是通过dt.Rows
中的每一行:
foreach (DataRow dr in dt.Rows)
{
comboBox1.Items.Add(dr["Roll"]);
}
答案 1 :(得分:0)
刚才想出答案,请看看底部的循环。
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
con.ConnectionString = "Data Source=.;Initial Catalog=StudentDetails;Integrated Security=True";
cmd.Connection = con;
cmd.CommandText = "select * from studet";
da.SelectCommand = cmd;
da.Fill(ds);
dt = ds.Tables[0];
dataGridView1.DataSource = dt;
////////////////////////////////////////////////////
DataRow dr = dt.NewRow();
for (int i = 0; i < dt.Rows.Count; i++)
{
dr[0] = dt.Rows[i][0];
comboBox1.Items.Add(dr[0]);
}
}