我想访问数据表的每个单元格。怎么样?

时间:2012-08-02 10:03:13

标签: c# datatable

使用C#,我想访问数据表中每一行的每个单元格。这样做的最佳做法是什么?

for (int i = 0; i <= 5; i++)
    {
        if (myQuantity[i]!=null && myQuantity[i].Length>0)
        {
            row = dt.NewRow();
            row["Name"] = myName[i];
            row["Quantity"] = myQuantity[i];
            row["Price"] = myPrice[i];

            c = Convert.ToInt32(myQuantity[i]);

            int price = Convert.ToInt32(myPrice[i]) * c;


            row["Amount"] = price;

            dt.Rows.Add(row);

        }
    }

2 个答案:

答案 0 :(得分:7)

您可以遍历访问每个单元格的行:

int numberOfColumns = dt.Columns.Count;

// go through each row
foreach (DataRow dr in dt.Rows)
{
    // go through each column in the row
    for (int i = 0; i < numberOfColumns; i++)
    {
        // access cell as set or get
        // dr[i] = "something";
        // string something = Convert.ToString(dr[i]);
    }
}

答案 1 :(得分:7)

您可以foreach使用DataRow循环以及DataColumn,以下行中的某些内容......

DataTable dt = new DataTable();

foreach(DataRow dr in dt.Rows)
    foreach (DataColumn dc in dt.Columns)
    {
        Console.WriteLine(dr[dc]);
    }