获取C#中DataGridView的选定行的第一列值

时间:2013-11-13 14:07:30

标签: c# datagridview

我使用以下代码获取所选数据网格视图结果的ID(第一个)列,并单击按钮

`DataGridViewSelectedCellCollection DGV = this.dgvSearch.SelectedCells;
for (int i = 0; i <= DGV.Count - 1; i++)
{
string ID = Convert.ToString(dgvSearch.CurrentRow.Cells[0].Value);
MessageBox.Show(ID); 
}`

我在消息框中收到ID,但与列号相同,我只想为每个选择行一次。

1 个答案:

答案 0 :(得分:2)

使用DataGridViewSelectedRowCollection代替DataGridViewSelectedCellCollection并循环选择的行数。在循环内部给出与你给出的相同的东西。将this.dgvSearch.SelectedCells替换为this.dgvSearch.SelectedRows ..

更新:

 DataGridViewSelectedRowCollection DGV =this.dgvSearch.SelectedRows;
  foreach (DataGridViewRow row in DGV)
  {
 DataRow myRow = (row.DataBoundItem as DataRowView).Row;
  string ID = Convert.ToString(myRow.Cells[0].Value);
  MessageBox.Show(ID); 

   }