且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在dataGridView C#中添加行和填充值

更新时间:2023-12-06 17:15:34

首先加载了DataGridView,然后需要将作为原始源的DataTable传递给类似于以下内容的方法:

Having first loaded your DataGridView you then need to pass the DataTable that was the initial source through to a method that looks similar to this:

private void addExtraRows(DataTable dT)
{

    DataTable newTable = dT.Clone();
    DataRow nR;
    int lastRow = dT.Rows.Count - 1;
    for (int i = 0; i < lastRow; i++)
    {
        if (dataGridView3.Rows[i].Cells[1].Value.ToString() == "1.1")
        {
            for (int j = i + 1; j < dT.Rows.Count; j++)
            {
                if (dT.Rows[j][2] == dT.Rows[i][2] && dT.Rows[j][3] == dT.Rows[i][3])
                {
                    nR = newTable.NewRow();
                    nR[0] = dT.Rows[i][0];
                    nR[1] = "1";
                    nR[2] = dT.Rows[i][2];
                    nR[3] = dT.Rows[i][3];
                    newTable.Rows.Add(nR);
                    break;
                }
            }
        }
        nR = newTable.NewRow();
        nR[0] = dT.Rows[i][0];
        nR[1] = dT.Rows[i][1];
        nR[2] = dT.Rows[i][2];
        nR[3] = dT.Rows[i][3];
        nR[4] = dT.Rows[i][4];
        newTable.Rows.Add(nR);
    }
    nR = newTable.NewRow();
    nR[0] = dT.Rows[lastRow][0];
    nR[1] = dT.Rows[lastRow][1];
    nR[2] = dT.Rows[lastRow][2];
    nR[3] = dT.Rows[lastRow][3];
    nR[4] = dT.Rows[lastRow][4];
    newTable.Rows.Add(nR);

    dataGridView3.DataSource = null;
    dataGridView3.Rows.Clear();
    dataGridView3.DataSource = newTable;
    return;
}

请注意,您可能需要更改dataGridView的名称!

Please note that you may need to change the name of the dataGridView!

编辑:

假设DataGridView的DataSource是一个DataTable,则可以将方法的开始更改为:

Assuming that the DataSource of your DataGridView is a DataTable then you can change the start of the method to:

private void addExtraRows()
{
    DataTable dT = (DataTable)dataGridView3.DataSource;
    DataTable newTable = dT.Clone();

现在,您要做的就是在网格加载后调用此例程。

Now all you have to do is to call this routine after your grid has loaded.