【问题标题】:How to remove rows in data grid view where checkbox is checked?如何删除选中复选框的数据网格视图中的行?
【发布时间】:2011-06-22 12:17:56
【问题描述】:

我正在使用 C# .NET 2.0 Visual Studio 2005。

我遇到了奇怪的问题。

有一个简单的窗口窗体,只有一个 DataGridView,其中 column1 为复选框 (DataGridViewCheckboxColumn)

然后如果单元格中的复选框被选中,我想删除选中的行。

听起来很简单,但它并没有以某种方式删除所有选中的行,而且我真的不明白为什么它会以这种方式运行。

例如,我有 5 行并选中了每行中的所有复选框,但它只删除了 3 行。有没有人见过这个?这是一个错误还是我做错了什么?

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //when I click the button, all checked row should be removed
        private void button1_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                if ((bool)row.Cells[0].Value)
                {
                    dataGridView1.Rows.Remove(row);
                }
            }
        }
    }
}

【问题讨论】:

  • 它是窗口窗体应用程序,我在项目探索中没有看到它
  • 对不起,正人先生,我的错误。 :)
  • 我认为反向运行 for 循环是更好更快的方法,因为您不会额外列出对象来存储 toDelete 行,而且您只需要一个循环即可完成整个任务。
  • @Charlie:感谢您的洞察力。我的网格删除行为异常的另一个原因是我没有提交更改。 myGrid.CommitEdit(DataGridViewDataErrorContexts.Commit);

标签: c# .net checkbox datagridview


【解决方案1】:

当删除一行时,行数也会减少,因此如果您将代码放入 for 循环并反向运行,它会正常工作,看看:

for (int i = dataGridView1.Rows.Count -1; i >= 0 ; i--)
{
    if ((bool)dataGridView1.Rows[i].Cells[0].FormattedValue)
    {
        dataGridView1.Rows.RemoveAt(i);
    }
}

【讨论】:

    【解决方案2】:

    您在迭代时修改了一个集合。

    使用删除列表而不是删除行。

    【讨论】:

    • 感谢您的快速回复,您能详细解释一下吗?我没有找到删除方法...
    【解决方案3】:

    您在迭代集合时正在修改它。试试这样

    List<DataGridViewRow> toDelete = new List<DataGridViewRow>();
    foreach (DataGridViewRow row in dataGridView1.Rows) {
        if (row.Cells[0].Value == true) {
            toDelete.Add(row);
        }
    }
    foreach (DataGridViewRow row in toDelete) {
        dataGridView1.Rows.Remove(row);
    }
    

    【讨论】:

    • 在上面的 if 语句中使用强制转换:if ((bool)row.Cells[0].Value)
    【解决方案4】:

    这个解决方案有一点错误,我修正了添加 1 行:)

    List<DataGridViewRow> toDelete = new List<DataGridViewRow>();
    
    foreach (DataGridViewRow row in dataGridView1.Rows) 
    {
      bool s = Convert.ToBoolean(row.Cells[0].Value) //added this line
    
      if (s == true) 
        {
            toDelete.Add(row);
        }
    }
    
    foreach (DataGridViewRow row in toDelete) 
    {
        dataGridView1.Rows.Remove(row);
    }
    

    【讨论】:

      【解决方案5】:

      @Chen Kinnrot,绝对有钱!当你运行你的函数时,你总是只会删除 n % 2 行,所以如果你有 10 行,那么你将删除 5,而 101 将是 51,等等。遍历集合以查找哪些复选框被选中,然后删除那些行。更好的解决方案是将事件附加到单击 button1 时自动运行的复选框。

      【讨论】:

        【解决方案6】:
        ASPXPAGE:
        <strong>Asp.Net : Delete Multiple Records form datagridview in one time<br />
                </strong>
        
                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
                    BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px"
                    CellPadding="4" EnableModelValidation="True" ForeColor="Black">
                    <Columns>
                        <asp:TemplateField>
                            <EditItemTemplate>
                                <asp:CheckBox ID="CheckBox1" runat="server" />
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:CheckBox ID="CheckBox1" runat="server" />
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:BoundField DataField="id" HeaderText="Sr No" />
                        <asp:BoundField DataField="doc_name" HeaderText="Name" />
                        <asp:BoundField DataField="doc_add" HeaderText="Address" />
                        <asp:BoundField DataField="doc_mob" HeaderText="Mobile No" />
                        <asp:BoundField DataField="doc_email" HeaderText="Email" />
                    </Columns>
                    <FooterStyle BackColor="#CCCC99" ForeColor="Black" />
                    <HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
                    <PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
                    <SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
                </asp:GridView>
                <br />
                <asp:Button ID="Button1" runat="server" Font-Size="12pt"
                    onclick="Button1_Click1" Text="Delete" />
                <br />
        
        
        
        Code Behind Page:
        SqlConnection conn = new SqlConnection(@"server=server-pc; database=HMS; integrated security=true");
            protected void Page_Load(object sender, EventArgs e)
            {
                if (IsPostBack == false)
                {
                    load_data();
                }
            }
        
           public void load_data()
            {
                SqlDataAdapter adp = new SqlDataAdapter("select * from doc_master", conn);
                DataSet ds = new DataSet();
                adp.Fill(ds);
                GridView1.DataSource = ds.Tables[0];
                GridView1.DataBind();
            }
           protected void Button1_Click1(object sender, EventArgs e)
           {
               CheckBox ch;
               for (int i = 0; i < GridView1.Rows.Count; i++)
               {
                   ch = (CheckBox)GridView1.Rows[i].Cells[0].Controls[1];
                   if (ch.Checked == true)
                   {
              int id = Convert.ToInt32(GridView1.Rows[i].Cells[1].Text);
              SqlCommand cmd = new SqlCommand("delete from doc_master where ID=" + id + " ", conn);
              conn.Open();
              cmd.ExecuteNonQuery();
              conn.Close();
                   }
               }
        
               load_data();
           }
        

        详细代码请访问: http://www.gtuguide.com/2014/05/deleting-multiple-rows-in-gridview.html

        【讨论】:

          【解决方案7】:
            protected void btnDelRow_Click(object sender, EventArgs e)
              {
                  #region Delete Row from data list Grid On Behalf of checkbox from dyanamically added grid
                  int ClSno = 0;  /*Use For Sitewise New Serial No*/
                  foreach (DataListItem dst in dstBillDetails.Items)
                  {
                      ClSno = ClSno + 1;        
                      Label lbl_SChkFlag = (Label)dst.FindControl("lblSChkFlag");        
                      GridView Grid_B = (GridView)dst.FindControl("GridB");
                      if (lbl_SChkFlag.Text == "0")
                      {
                          int Newbillflg = 0;/**If SiteCode Is Zero Then Usefull**/
                          foreach (GridViewRow gvr in Grid_B.Rows)
                          {
                              #region
                              Label lbl_grdId = (Label)gvr.FindControl("lblgrdId");
                              CheckBox chk_dstgrdlst = (CheckBox)gvr.FindControl("chkdstgrdlst");
                            
                              if (chk_dstgrdlst.Checked == true)
                              {
                                  if (Grid_B.Rows.Count > 1)
                                  {
                                  
                                      gvr.Style["display"] = "none";
                                      lbl_grdId.Text = "1";                          
                                  }
                                  else
                                  {/**When Gridview Row is Zero**/
                                      Grid_B.Visible = false;
                                      lbl_grdId.Text = "1";
                                      /**When Gridview Row is Zero**/
                                  }
                                
                              }
                              #endregion
                          }
                      }
                  }
                  #endregion
              }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2022-10-25
            • 2010-11-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-03-27
            • 1970-01-01
            • 2011-08-06
            相关资源
            最近更新 更多