I need to get all the rows in a Da开发者_如何学JAVAtaGridView 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
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.
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.
foreach(DataGridViewRow row in dataGridView.Rows)
{
//Your code here
}
精彩评论