C# DataRow 中的 DataColumn 名称(不是 DataTable)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12823371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:33:23  来源:igfitidea点击:

DataColumn Name from DataRow (not DataTable)

c#.netdatarowdatacolumn

提问by James Dean

I need to iterate the columnname and column datatype from a specific row. All of the examples I have seen have iterated an entire datatable. I want to pass a single row to a function to do a bunch of conditional processing. I want to separate the conditional processing for ease of readability.

我需要从特定行迭代列名和列数据类型。我见过的所有示例都迭代了整个数据表。我想将一行传递给一个函数来进行一堆条件处理。为了便于阅读,我想将条件处理分开。

This is what I have:

这就是我所拥有的:

private void doMore(DataRow dr)
{
    foreach (DataColumn c in dr.ItemArray)  //loop through the columns. 
    {
        MessageBox.Show(c.ColumnName.ToString());
    }
}

The error returned is

返回的错误是

System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Data.DataColumn'.

System.InvalidCastException:无法将“System.String”类型的对象转换为“System.Data.DataColumn”类型。

How would I get the column name from the row or do I have no choice and must pass the entire datatable to the function?

我如何从行中获取列名,或者我别无选择并且必须将整个数据表传递给函数?

采纳答案by Daniel Hilgarth

You would still need to go through the DataTableclass. But you can do so using your DataRowinstance by using the Tableproperty.

你仍然需要通过DataTable课程。但是您可以DataRow通过使用Table属性来使用您的实例。

foreach (DataColumn c in dr.Table.Columns)  //loop through the columns. 
{
    MessageBox.Show(c.ColumnName);
}

回答by Kamil Krasinski

use DataTable object instead:

改用 DataTable 对象:

 private void doMore(DataTable dt)
    {
    foreach(DataColumn dc in dt.Columns)
    {
    MessageBox.Show(dc.ColumnName);
    }
    }

回答by Mark Harrell

You need something like this:

你需要这样的东西:

foreach(DataColumn c in dr.Table.Columns)
{
  MessageBox.Show(c.ColumnName);
}

回答by Rob Hardy

You can make it easier in your code (if you're doing this a lot anyway) by using an extension on the DataRow object, like:

您可以通过在 DataRow 对象上使用扩展来简化代码(如果您经常这样做的话),例如:

static class Extensions
{
    public static string GetColumn(this DataRow Row, int Ordinal)
    {
        return Row.Table.Columns[Ordinal].ColumnName;
    }
}

Then call it using:

然后使用以下方法调用它:

string MyColumnName = MyRow.GetColumn(5);