2010-08-23 75 views
6

我有一個表格,我在數據網格視圖控件中顯示。用戶從控件中選擇一行並按下一個按鈕。我需要從該行檢索單元格並將它們存儲爲字符串。如何使用SelectedRows從數據網格視圖中獲取選定的行數據?

究竟如何使用SelectedRow方法獲取數據?我已經爲此工作了好幾個小時,而且我已經完成了我的繩索。以下是我嘗試過的一些示例:

DataGridViewCellCollection selRowData = dataGridView1.SelectedRows[0].Cells; 

如果我嘗試訪問selRowData [x],返回值不包含我的數據。

+0

回答[這裏]通過所有小區建立一個文本串。 [1]:http://stackoverflow.com/a/10525686 – ZMan 2013-01-21 20:43:55

回答

7

你接近 - 你需要通過它的索引引用每個Cell並返回其Value屬性:

string firstCellValue = dataGridView1.SelectedRows[0].Cells[0].Value; 
string secondCellValue = dataGridView1.SelectedRows[0].Cells[1].Value; 

1

嘗試使用DGV的項目元素。

dgvFoo.Item(0, dgvFoo.CurrentRow.Index).Value 

這將返回第一項的值。你可以把它放在一個for循環中以獲得全部。

另一種選擇是使用對象上的SelectedRows集合並遍歷每個選定的行(或者只是您的案例中的一個)。

1

那麼有沒有datagridview的項目屬性.. @周杰倫裏格斯的解決方案是更好的... ...以下解決方案也適用:

string firstCellValue = dataGridView1[0,dataGridView1.CurrentRow.Index].Value.ToString(); 
string secondCellValue = dataGridView1[0,dataGridView1.CurrentRow.Index].Value.ToString(); 

這裏0是第一列和dataGridView1.CurrentRow.Index是當前行從哪裏獲得價值。

1

如果你想要的數據和數據很可能綁定到數據源,那麼可能我建議你從選擇鍵,然後你可以用它來訪問數據,你喜歡的任何方式:

dataGridView.SelectedDataKey.Value; 
0

也許這是更合適的解決方案中使用點擊的行的單元格的值:[1]進行迭代

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) 
{ 
    if (e.RowIndex > -1) 
    { 
    var val = this.dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString(); 
    } 
} 
相關問題