2
votes

I need to get all the rows in a DataGridView in a foreach function. How can I do this?

I.E. foreach() for each row, so for each row I could run code that would utilize the first and second column data.

This is in c#

Thanks, Christian

3
So much better to access the DataSource the Grid is bound to. - Henk Holterman
It's not bound to one. Its supposed to be populated by the user. - Christian Stewart
I.E. I put a datagrid view in a windows Form and am letting the user create values and then get data from it. - Christian Stewart
Very rarely a good idea. A grid is a control to Present data, not a container to Store data. It can be done but that doesn't mean it's a good idea. - Henk Holterman

3 Answers

2
votes

Remember, it's always a good practice to bind the DataGridView to a data source, and then using the data source to do anything data-related. This keeps you clean from interacting with the datagrid.

2
votes

I think the best way of accessing this data is either through the Data Source:

dataGridView.DataSource = someData;
someData.property;

OR, if the user is entering data on the page, you can access from the FindControl method:

name = ((TextBox)dataGridView.Rows[e.RowIndex].FindControl("name")).Text;

In this case, if you've raised an event for a specific row, it will return EventArgs e, with a specific RowIndex. Then you can access the Column values via the ControlID within the column, such as <asp:TextBox id="name" runat="server" /> from .FindControl("name").

The important thing to remember is that you have to cast that object back to the type that it should be from the .FindControl() method.

1
votes
foreach(DataGridViewRow row in dataGridView.Rows)
{
     //Your code here
}