2

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

4
  • So much better to access the DataSource the Grid is bound to. Commented Jun 7, 2011 at 17:31
  • It's not bound to one. Its supposed to be populated by the user. Commented Jun 7, 2011 at 17:32
  • I.E. I put a datagrid view in a windows Form and am letting the user create values and then get data from it. Commented Jun 7, 2011 at 17:33
  • 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. Commented Jun 7, 2011 at 18:01

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

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

1 Comment

I know this. How can I get the data from Coloum 1 and Colum 2 from this? Strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.