我创建了一个表单,其中有4个标签教师ID,教师姓名,部门和说明以及相应的文本框。我已经通过ADD按钮(使用插入查询)在数据库中插入了值。我已经采用数据网格视图来显示数据。
问题是现在我想要当iIselect一行datagridview然后它应该在各自的文本框中显示u =其数据。 我尝试过以下代码,但无法正确编写代码。
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=SW-PC-20;Integrated security =SSPI;Initial catalog=institute");
con.Open();
SqlCommand com = new SqlCommand("select * from teacher2", con);
SqlDataReader dr = com.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dr.Close();
dataGridView1.DataSource = dt;
if (dr.HasRows)
dr.Read();
txtteacherid.Text = dr[0].ToString();
txtteachername.Text = dr[1].ToString();
txtdepartment.Text = dr[2].ToString();
txtdescription.Text = dr[3].ToString();
}
答案 0 :(得分:0)
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex > -1)
{
txtteacherid.Text = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
txtteachername.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
txtdepartment.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
txtdescription.Text = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
}
}