【问题标题】:How can I get value of a specific cell in DataTable in c#?如何在 c# 中获取 DataTable 中特定单元格的值?
【发布时间】:2016-01-30 11:33:47
【问题描述】:

我是 C# 新手,并且使用 Windows 窗体。

我有一个数据表,如屏幕截图所示,我想根据Button_Name 列值获取button_Text 列中特定单元格的值并将其保存在字符串中。我知道我可以使用此代码:

string s = DataTable.Rows[2][1];

但我不想使用它,因为我不想使用括号之间的数字来索引单元格值,而是我想使用 Button_Name 列值和 button_Text 列名来索引单元格值. 例如:

string s = DataTable.Rows[ButtonUC1_3][Button_Text]; // but it gives error : "Argument1: can not convert from string to int"

我希望它足够清楚。任何人都知道如何实现这一目标?谢谢你

【问题讨论】:

    标签: c#


    【解决方案1】:

    使用LINQ to DataSet 可以使用列名

    string value = dataTable.AsEnumerable()
                   .Where((row) => row.Field<string>("button_Name").Equals("ButtonUC_1"))
                   .Select((row) => row.Field<string>("button_Text"))
                   .FirstOrDefault();
    

    【讨论】:

    • 无法将类型'System.Data.EnumerableRowCollection'隐式转换为'string'
    • 您添加了FirstOrDefault 吗? WhereSelect 将返回值的集合。调用 FirstOrDefaultFirst 将返回集合中的第一项
    【解决方案2】:

    这里的行必须是整数格式,但允许列字符串, 以下是错误

    string s = DataTable.Rows["ButtonUC1_3"]["Button_Text"]; 
    

    正确的格式是,

    string s = DataTable.Rows[2]["Button_Text"]; 
    

    它会给单元格值,。

    【讨论】:

      【解决方案3】:

      DataTable Rows 没有名称,它们仅按数字索引。如果要通过指定的名称访问行,则需要使用自己的映射,例如var rowMapping = new Dictionary&lt;string,int&gt;() { { ButtonUC1_3, 0}, ... } 然后像DataTable.Rows[rowMapping[ButtonUC1_3]][Button_Text] 这样访问DataTable。

      显然,这不是唯一的方法,您可以定义枚举、整数常量等。这完全取决于您拥有多少行以及如何使用 DataTable。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-07
        • 2014-07-21
        • 1970-01-01
        • 2012-07-18
        • 1970-01-01
        • 2018-05-30
        • 1970-01-01
        • 2014-08-29
        相关资源
        最近更新 更多