2011-05-02 35 views
0

我已經創建了一個表單,其中有4個標籤的教師ID,教師姓名,部門和說明以及相應的文本框。我通過ADD按鈕(使用插入查詢)將值插入到數據庫中。我使用datagrid視圖來顯示數據。如何使用數據網格視圖獲取文本框中顯示的特定數據

現在的問題是,我想當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
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(); 
       } 

    } 
相關問題