在dataGridView C#中添加行和填充值 [英] Add row and fill value in dataGridView C#
问题描述
我有问题。我想添加条件为row [i] .value = 1.1的新行,然后在row [i]上方添加正位置并填充3个单元格的值(其他单元格为空白)。在[![输入图像描述之前在这里] [1]] [1]在[![在此处输入图片描述之后]
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]
推荐答案
首先加载了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.
这篇关于在dataGridView C#中添加行和填充值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!