使用 foreach 读取 DataTable,并将这些值放入 C# 中的 DataGridView 中

本文关键字:中的 DataGridView 读取 foreach DataTable 使用 | 更新日期: 2023-09-27 17:57:24

这里是我的数据表public DataTable GetValues()

    dt.Columns.Add("num");
    dt.Columns.Add("nam");
    dt.Columns.Add("amt");
    DataRow row = dt.NewRow();
    DataRow row2 = dt.NewRow();
    row[0] = 1;
    row[1] = "cha";
    row[2] = 20;
    row2[0] = 2;
    row2[1] = "nip";
    row2[2] = 22;
    dt.Rows.Add(row);
    dt.Rows.Add(row2);
    return dt;

我在表单加载事件中创建了三列

private void testWin_Load(object sender, EventArgs e)
        dataGridView1.Columns.Add("Number", "Number");
        dataGridView1.Columns.Add("Name", "Name");
        dataGridView1.Columns.Add("Amount", "Amount");

我正在像这样阅读数据表

private void button1_Click(object sender, EventArgs e)
    DataTable dt = new DataTable();
    dt = _testClass.GetValues();
    foreach (DataRow row in dt.Rows)
    {
        string v = row["num"].ToString();
        string v1 = row["nam"].ToString();
        string v2 = row["amt"].ToString();
        foreach (DataGridViewRow gridRow in dataGridView1.Rows)
        {
            DataGridViewCell cell1 = gridRow.Cells[0] as DataGridViewCell;
            DataGridViewCell cell2 = gridRow.Cells[1] as DataGridViewCell;
            DataGridViewCell cell3 = gridRow.Cells[2] as DataGridViewCell;
            cell1.Value = v;
            cell2.Value = v1;
            cell3.Value = v2;
        }
    }

但它只显示数据网格视图中的最后一个值我的问题是什么

谢谢

使用 foreach 读取 DataTable,并将这些值放入 C# 中的 DataGridView 中

尝试此代码希望对您有所帮助

foreach (DataRow row in dt.Rows)
{
     dataGridView1.Rows.Add(row);
    //string v = row["num"].ToString();
    //string v1 = row["nam"].ToString();
    //string v2 = row["amt"].ToString();
    //foreach (DataGridViewRow gridRow in dataGridView1.Rows)
    //{
        //DataGridViewCell cell1 = gridRow.Cells[0] as DataGridViewCell;
        //DataGridViewCell cell2 = gridRow.Cells[1] as DataGridViewCell;
        //DataGridViewCell cell3 = gridRow.Cells[2] as DataGridViewCell;
        //cell1.Value = v;
        //cell2.Value = v1;
        //cell3.Value = v2;
    //}
}

尝试,

dataGridView1.DataSource = dt;
dataGridView1.DataBind();

dt 是数据表。