Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

Add row and fill value in dataGridView C#

I have a problem. I want to add new row with condition if row[i].value ="1.1" then i add row has positon above row[i] and fill value for 3 cells(other cells is blank).Before [![enter image description here][1]][1] After [![enter image description here][2]][2]

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

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

Edit:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...