数据表的访问单元格值


Answers:


133

如果需要对单元格值的弱引用:

object field = d.Rows[0][3]

要么

object field = d.Rows[0].ItemArray[3]

应该做

如果需要强类型引用(在您的情况下为字符串),则可以使用DataRowExtensions.Field扩展方法:

string field = d.Rows[0].Field<string>(3);

(在这种情况下,请确保名称空间中列出了System.Data)

索引基于0,因此我们首先访问第一行(0),然后访问该行的第四列(3)


4
@OP请记住,当像这样硬编码值时,您经常需要首先检查以确保确实有足够的行/列。
Servy 2012年

1
另请参阅stackoverflow.com/a/13816531/638977它建议int number = dt.Rows[i].Field<int>(j);
Behzad Ebrahimi


13

您也可以尝试(第4列的第一个单元格):

dt.Rows[0][3]


7

数据d位于d的第0行和第3列:

DataTable table;
String d = (String)table.Rows[0][3];

1
public V[] getV(DataTable dtCloned)
{

    V[] objV = new V[dtCloned.Rows.Count];
    MyClasses mc = new MyClasses();
    int i = 0;
    int intError = 0;
    foreach (DataRow dr in dtCloned.Rows)
    {
        try
        {
            V vs = new V();
            vs.R = int.Parse(mc.ReplaceChar(dr["r"].ToString()).Trim());
            vs.S = Int64.Parse(mc.ReplaceChar(dr["s"].ToString()).Trim());
            objV[i] = vs;
            i++;
        }
        catch (Exception ex)
        {
            //
            DataRow row = dtError.NewRow();
            row["r"] = dr["r"].ToString();
            row["s"] = dr["s"].ToString();
            dtError.Rows.Add(row);
            intError++;
        }
    }
    return vs;
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.