Click here to Skip to main content
15,885,668 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.
C#
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);
    }
}
Posted
Updated 20-Nov-12 9:32am
v2

SQL
if (this.dataGridView1.SelectedRows.Count > 0)
           {
               bs.RemoveAt(this.dataGridView1.SelectedRows[0].Index);
           }
           else
           {
               MessageBox.Show("Please select one row");
           }
 
Share this answer
 
Try this
C#
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);
                
            }


C#
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);
}
 
Share this answer
 
v2
Comments
meme_307 21-Nov-12 7:30am    
Tank's it works good :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900