简体   繁体   English

如何从datagridview中删除行?

[英]How to delete the row from datagridview?

Friends, I'm using datagridview in my windows C# application.朋友们,我在 Windows C# 应用程序中使用了 datagridview。 We know that When the form with datagridview is loaded a default row is created in the grid.我们知道,当加载带有 datagridview 的表单时,会在网格中创建一个默认行。 If we type anything in any cell(I've total 6 columns, 2 hidden columns), a new row is created.如果我们在任何单元格中输入任何内容(我总共有 6 列,2 个隐藏列),则会创建一个新行。 But if we delete the entry the newly created row is not deleted.但是,如果我们删除条目,则不会删除新创建的行。 In this way we can create as many row we want without keeping any value inside any cell.通过这种方式,我们可以创建任意数量的行,而无需在任何单元格中保留任何值。 I want the datagridview to maximum create 2 such rows and when in both the rows, no value is present, the last row to be deleted (so that grid will have 1 row without any data in it).我希望 datagridview 最多创建 2 个这样的行,并且当在两行中都没有值时,要删除最后一行(这样网格将有 1 行没有任何数据)。 I've tried to remove row in datagridview1_CellValueChanged event, but it's not working.我试图删除 datagridview1_CellValueChanged 事件中的行,但它不起作用。 Which event should I use and how can I get the desired functionality?我应该使用哪个事件以及如何获得所需的功能? Please help.请帮忙。

尝试这个:

DataGridView1.Rows.Remove(row);

If you loop using the same grid RowCount it won't work如果您使用相同的网格 RowCount 循环,它将不起作用

  for(int i = 0;i<dataGridMaster.Rows.Count;i++)
            {
               dataGridMaster.Rows.RemoveAt(i);
            }

It Will not do the job correctly because the Count of rows changes while looping.它不会正确完成工作,因为循环时行数会发生变化。

Instead assign the number to a local variable like:而是将数字分配给局部变量,例如:

Int loopNum = dataGridMaster.Rows.Count;
for(int i = 0;i<loopNum ;i++)
            {
               dataGridMaster.Rows.RemoveAt(i);
            }

A default row is automatically added to allow for user input.自动添加默认行以允许用户输入。 If you don't want this, set the DataGridView AllowUserToAddRows property to false.如果您不想这样做,请将 DataGridView AllowUserToAddRows属性设置为 false。

dataGridView.AllowUserToAddRows = false;

Making it effectively a read-only grid.使其有效地成为只读网格。

We have two function to remove rows from DataGridView我们有两个函数可以从 DataGridView 中删除行

dataGridView1.Rows.Remove();
dataGridView1.Rows.RemoveAt();

you can provide the index of the row as parameter to remove the row.您可以提供该行的索引作为参数来删除该行。

You can give in Validating or Validated event of DataGridView您可以提供 DataGridView 的 Validating 或 Validated 事件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM