datagride删除代码中的问题 [英] problem in datagride deleting code

查看:69
本文介绍了datagride删除代码中的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码不会从datagrid中随机删除
我需要选择要删除的任何行,但是此代码仅从第一行然后第二行删除,等等.

This code not delete from datagrid Randomly
I need to select any row to delete but this code delete just from first row then second row etc.

for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
    DataGridViewRow dr = dataGridView1.Rows[i];
    if (dr.Selected == true)
    {
        try
        {
            SqlCommand cmd = new SqlCommand("Delete from calender where ID='" + dataGridView1.SelectedRows[i].Cells[2].Value + "'", con);
            cmd.ExecuteNonQuery();
            con.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
        dataGridView1.Rows.RemoveAt(i);
    }
}

推荐答案

if (this.dataGridView1.SelectedRows.Count > 0)
           {
               bs.RemoveAt(this.dataGridView1.SelectedRows[0].Index);
           }
           else
           {
               MessageBox.Show("Please select one row");
           }


试试这个
for (int i = 0; i < dataGridView1.SelectedRows.Count; i++)
            {              
               
                    try
                    {
                        SqlCommand cmd = new SqlCommand("Delete from calender where ID='" + dataGridView1.SelectedRows[i].Cells[2].Value + "'", con);
                        cmd.ExecuteNonQuery();
                        con.Close();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                    dataGridView1.Rows.RemoveAt(i);
                
            }





foreach(DataGridViewRow dr in dataGridView1.SelectedRows)
{
 try
                    {
                        SqlCommand cmd = new SqlCommand("Delete from calender where ID='" + dr.Cells[2].Value + "'", con);
                        cmd.ExecuteNonQuery();
                        con.Close();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                    dataGridView1.Rows.RemoveAt(i);
}


这篇关于datagride删除代码中的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆