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

C# 使用foreach读取DataTable,并将值放入C中的DataGridView中#,c#,C#,这里是我的数据表 公共数据表GetValues() 我在表单加载事件中创建了三列 private void testWin_Load(object sender, EventArgs e) dataGridView1.Columns.Add("Number", "Number"); dataGridView1.Columns.Add("Name", "Name"); dataGridView1.Columns.Add("Amount", "Amo

这里是我的数据表 公共数据表GetValues()

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

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;
        }
    }
但它只显示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;
    //}
}
试试看


dt是数据表。

您在datagridview循环中所做的只是一遍又一遍地更改同一行。datagridview不需要循环。只需使用
dataGridView1.Rows.Add()
函数即可
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();