0

使用 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);

        }
    }
4

2 回答 2

8

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

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]);
    }
}
于 2012-08-02T10:06:46.543 回答
8

您可以在下一行使用foreach循环 forDataRow以及, Something ...DataColumn

DataTable dt = new DataTable();

foreach(DataRow dr in dt.Rows)
    foreach (DataColumn dc in dt.Columns)
    {
        Console.WriteLine(dr[dc]);
    }
于 2012-08-02T10:20:45.780 回答