1

I have a DataGridView that looks like the following.

enter image description here

I am required to get ID value of every row and perform an operation with it in every loop. I am able to get the ID value if I select a particular row. However what I am trying to do is basically select all the rows pro-grammatically and get the ID value in every count of my for loop.

Ideally I'd get 2645 in my first iteration, 1723 in the second iteration and so on.

What I tried so far is:

if (dataGridView1.SelectedCells.Count > 0)
{
    int selectedrowindex = dataGridView1.SelectedCells[0].RowIndex;
    DataGridViewRow selectedRow = dataGridView1.Rows[selectedrowindex];
    string IDStr = Convert.ToString(selectedRow.Cells["ID"].Value);               

    //an operation with the ID Value               
}

This only worked for a single row and when I selected the row manually. For every row in the DataGridView, I tried to add dataGridView1.SelectAll() and looped inside foreach(DataGridViewRow row in dataGridView1.SelectedCells) and performed all the steps above but that did not work either.

What am I doing wrong here? Any idea/help would be greatly appreciated. I am happy to clarify if any info is unclear in the question.

CodeBreaker
  • 87
  • 2
  • 11
  • 1
    why are you interested only in the selected values? It sounds like you want to have them all ?=!. How do you insert your data into the `DataGrundView` ? It would be adviseable to operate on the source data and extract the desired Id's from there. – Mong Zhu Jul 19 '19 at 19:52
  • Yes, the bottom line is to have the entire first column. Selecting all values was just my approach since it worked for single row selection. I am getting a response from a SOAP request which I bind into a datagridview. That's where the data is from. If there is an easier way to get the column, i.e w/o selection, I am open to look into that too. – CodeBreaker Jul 19 '19 at 19:59
  • please post exactly this piece of code(the binding) and show us the source collection. But in the end I still would advise to select from the source rather than hiking through the `DataGridView` – Mong Zhu Jul 19 '19 at 20:01

1 Answers1

0

have not tested this code but something like this should work

if (dataGridView1.SelectedCells.Count > 0)
{
    foreach (GridViewRow row in dataGridView1.Rows)
    {
        int id = row[0].text;
    }
}

put a breakpoint and see if it gets the id, hope this helps

Omar
  • 48
  • 2
  • 7