简体   繁体   中英

Get First Column Values of Selected Rows of DataGridView in C#

I am using following code to Get ID(First) Column of the Selected Data Grid View Result with Button Click

`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); 
}`

I am getting ID in message box but for as same as the Column number of times, I just want it for once for each select row.

use DataGridViewSelectedRowCollection instead of DataGridViewSelectedCellCollection and loop through the no of rows selected. inside the loop just give the same what u have given. replace this.dgvSearch.SelectedCells with this.dgvSearch.SelectedRows ..

update:

 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); 

   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM