简体   繁体   English

C# 从 DataGridView 获取行

[英]C# Get Rows From DataGridView

I need to get all the rows in a DataGridView in a foreach function.我需要在 foreach function 中获取 DataGridView 中的所有行。 How can I do this?我怎样才能做到这一点?

IE foreach() for each row, so for each row I could run code that would utilize the first and second column data. IE foreach() 用于每一行,因此对于每一行,我都可以运行利用第一列和第二列数据的代码。

This is in c#这是在 c#

Thanks, Christian谢谢,克里斯蒂安

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.请记住,将 DataGridView 绑定到数据源,然后使用该数据源执行与数据相关的任何事情始终是一个好习惯。 This keeps you clean from interacting with the datagrid.这使您无需与数据网格进行交互。

I think the best way of accessing this data is either through the Data Source :我认为访问这些数据的最佳方式是通过Data Source

dataGridView.DataSource = someData;
someData.property;

OR, if the user is entering data on the page, you can access from the FindControl method:或者,如果用户在页面上输入数据,您可以从FindControl方法访问:

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 .在这种情况下,如果您为特定行引发了事件,它将返回带有特定RowIndexEventArgs e Then you can access the Column values via the ControlID within the column, such as <asp:TextBox id="name" runat="server" /> from .FindControl("name") .然后,您可以通过列内的ControlID访问列值,例如.FindControl("name")中的<asp:TextBox id="name" runat="server" />

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.要记住的重要一点是,您必须将 object 转换回它应该来自.FindControl()方法的类型。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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