一:将数据绑定到dataGridView控件上。
string sqlconn = "server=.;database=student;integrated security=true"; try { string sqlcom = "select * from student_info"; SqlConnection conn = new SqlConnection(sqlconn); SqlDataAdapter da = new SqlDataAdapter(sqlcom, conn); DataSet ds = new DataSet(); da.Fill(ds); dataGridView1.DataSource = ds.Tables[0].DefaultView; dataGridView1.AllowUserToAddRows = false; conn.Close(); }
二:点击dataGridView的某一行将改行数据对应显示在textBox上。
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { try { snoTextBox.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells["stu_sno"].Value.ToString(); nameTextBox.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells["stu_name"].Value.ToString(); sexTextBox.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells["stu_sex"].Value.ToString(); ageTextBox.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells["stu_age"].Value.ToString(); } catch (Exception a) { MessageBox.Show(a.ToString()); } }