2013-03-14 91 views

回答

8

您必須執行的SelectionChanged事件,然後檢查是否選擇了哪一行。

private void dataGridView_SelectionChanged(object sender, EventArgs e) 
{ 
    DataGridViewCell cell = null; 
    foreach (DataGridViewCell selectedCell in dataGridView.SelectedCells) 
    { 
     cell = selectedCell; 
     break; 
    } 
    if (cell != null) 
    { 
     DataGridViewRow row = cell.OwningRow; 
     idTextBox.Text = row.Cells["ID"].Value.ToString(); 
     nameTextBox.Text = row.Cells["Name"].Value.ToString(); 
     // etc. 
    } 
} 
+0

日Thnx @Nolonar但我在C#我不知道如何使用新:S:秒。 FirstOrDefault不在C#中接受:S – user2160781 2013-03-14 10:39:13

+0

@ user2160781您說得對,'DataGridViewSelectedCellCollection'沒有實現'FirstOrDefault()'方法。對此我很抱歉。我更新了我的答案,也許這次它會解決。 – Nolonar 2013-03-14 12:19:34

+0

非常感謝你:)這是作品:) – user2160781 2013-03-14 13:29:11

3

註冊網格的MouseClick事件並使用以下代碼。

private void dataGridView1_MouseClick(object sender, MouseEventArgs e) 
{ 
    DataGridViewRow dr = dataGridView1.SelectedRows[0]; 
    textBox1.Text = dr.Cells[0].Value.ToString(); 
    // or simply use column name instead of index 
    //dr.Cells["id"].Value.ToString(); 
    textBox2.Text = dr.Cells[1].Value.ToString(); 
    textBox3.Text = dr.Cells[2].Value.ToString(); 
    textBox4.Text = dr.Cells[3].Value.ToString(); 
} 

,並添加下面一行在你的加載事件

dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; 
0
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) 
{ 
    //it checks if the row index of the cell is greater than or equal to zero 
    if (e.RowIndex >= 0) 
    { 
     //gets a collection that contains all the rows 
     DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex]; 
     //populate the textbox from specific value of the coordinates of column and row. 
     txtid.Text = row.Cells[0].Value.ToString(); 
     txtname.Text = row.Cells[1].Value.ToString(); 
     txtsurname.Text = row.Cells[2].Value.ToString(); 
     txtcity.Text = row.Cells[3].Value.ToString(); 
     txtmobile.Text = row.Cells[4].Value.ToString(); 

    } 

}