[英]Add new blank row to datagridview c#
我有一个DataGridView
,它有一个DataTable
作为DataSource
。 现在我想在DataGridView
插入一个新的空行并使其完全变黑(如分隔线)。 我试图复制一行并将其设为黑色:
Datagridview1.rows.insertcopies(2,2,1);
但是我收到了这个错误:
当控件是数据绑定时,无法以编程方式将行添加到datagridview的rows集合中。
如何保持DataGridView
的方式,只需插入一个空行?
澄清 :
我想做一个分隔线。 我找不到任何解决方案,所以我想做一个空行并使其变黑。 使用:
for(int i=0;i<datagridview1.Rows.Count-1;i++)
{
if(datagridview1.Rows[i].Cells[1].formattedvalue.ToString() != datagridview1.Rows[i+1].Cells[1].formattedvalue.ToString())
{
//here I need to make a divider.
}
}
虽然你可以添加一个空白行作为分隔符,但这似乎更像是对我的黑客攻击。 相反,我会为现有的单元格边框着色。
这实际上比我预期的要花费更多 - 我认为它就像在行分隔器上设置颜色一样容易,但显然这不是它的工作原理 。
但您仍然可以通过以下方式自行绘制:
this.dataGridView1.CellPainting += DataGridView1_CellPainting;
同样,由于您对分隔符的绘制依赖于单元格值,因此您需要处理:
this.dataGridView1.CellValueChanged += DataGridView1_CellValueChanged;
我们的想法是检查您的条件(将所需列中的单元格值与同一列中的下一个单元格值进行比较),并在需要时为需要分隔符的行中的每个单元格绘制分隔符。 当条件列中的单元格值更改时,其整行应该无效,以触发该行中的每个单元格进行重新绘制。 同样,前一个应该是无效的,以防它绘制分频器的条件现在也改变了。
private void DataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex >= 0 && e.RowIndex != this.dataGridView1.Rows.Count - 1)
{
DataGridViewRow thisRow = this.dataGridView1.Rows[e.RowIndex];
DataGridViewRow nextRow = this.dataGridView1.Rows[e.RowIndex + 1];
if (thisRow.Cells[1].FormattedValue.ToString() != nextRow.Cells[1].FormattedValue.ToString())
{
e.Paint(e.ClipBounds, DataGridViewPaintParts.All);
Rectangle divider = new Rectangle(e.CellBounds.X, e.CellBounds.Y + e.CellBounds.Height - 2, e.CellBounds.Width, 2);
e.Graphics.FillRectangle(Brushes.Black, divider);
e.Handled = true;
}
}
}
private void DataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 1)
{
if (e.RowIndex > 0)
{
this.dataGridView1.InvalidateRow(e.RowIndex - 1);
}
this.dataGridView1.InvalidateRow(e.RowIndex);
}
}
相反,您也可以使用RowPrePaint
而不是RowPrePaint
来执行此CellPainting
,但最终您会遇到以下可能性:
这个错误几乎是自我解释的,我可以想到一个可以给你最终结果的解决方法,但它真的很“丑陋”,可能会破坏未来操作中的数据,所以我不确定我会推荐它。
DataRow empty = table.NewRow();
table.Rows.Add(empty);
您可以在DataTable中添加新行并再次绑定它! 就像是
DataRow rd = ds.Tables[0].NewRow();
ds.Tables[0].Rows.Add(rd);
GridView1.DataSource = ds;
GridView1.DataBind();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.