-1
private void btnDelete_Click(object sender, EventArgs e)
{

int i;
i = dataGridView1.SelectedCells[0].RowIndex;

OleDbConnection con = new OleDbConnection(constr);  
OleDbCommand delcmd = new OleDbCommand();
if (dataGridView1.Rows.Count > 1 && i != dataGridView1.Rows.Count - 1)
{
      delcmd.CommandText = "DELETE FROM tb1 WHERE ID=" + dataGridView1.SelectedRows[i].Cells[0].Value.ToString() + "";
      con.Open();
      delcmd.Connection = con;
      delcmd.ExecuteNonQuery();
      con.Close();
      dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[i].Index);
      MessageBox.Show("Row Deleted");
}

}

this is my code for deleting the seleted row from datagridview and database but when i click on the delete button it is showing this error...

"Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index"

Plz help me the code...

4
  • 1
    Where is the error thrown? Is it at i = dataGridView1.SelectedCells[0] ? Commented Jan 10, 2014 at 7:01
  • this error is thrown at this command ... delcmd.CommandText = "DELETE FROM tb1 WHERE ID=" + dataGridView1.SelectedRows[i].Cells[0].Value.ToString() + ""; Commented Jan 10, 2014 at 7:10
  • Are you sure? Because you just commented a minute ago that it was i = dataGridView1.SelectedCells[0] line. Commented Jan 10, 2014 at 7:12
  • yes i am sure it is showing error on the delete command line Commented Jan 10, 2014 at 7:17

4 Answers 4

2

Exploring DataGridView manually to fill and then access data (I mean picking up values from cells), as well as ignoring using for disposables, as well as using string concatenation instead of parametrized queries, is a direct way to hell.

I strongly recommend you to use data binding and parametrized queries.
Declare an entity type, whose instances will be displayed in DGV:

public class MyEntity
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Configure DGV columns to be data-bound (for the sample, set DataPropertyName property to "Id" and "Name" respectively) and set DGV data source:

        // your application fills this collection using data from database
        var source = new List<MyEntity>
        {
            new MyEntity { Id = 1, Name = "Apple" },
            new MyEntity { Id = 2, Name = "Orange" },
            new MyEntity { Id = 3, Name = "Plum" },
            new MyEntity { Id = 4, Name = "Peach" },
        };

        dataGridView1.DataSource = new BindingList<MyEntity>(source);

When you want to delete item from DGV, use underlying data source instead of picking up data from the view:

    private void DeleteSelectedItem()
    {
        if (dataGridView1.SelectedRows.Count == 0)
        {
            return;
        }

        var itemToDelete = (MyEntity)dataGridView1.SelectedRows[0].DataBoundItem;

        using (var connection = new OleDbConnection("..."))
        {
            connection.Open();

            using (var command = new OleDbCommand("DELETE FROM tb1 WHERE ID = ?", connection))
            {
                // delete item from database
                command.Parameters.AddWithValue("@Id", itemToDelete.Id);
                command.ExecuteNonQuery();

                // delete item from datasource and update DGV
                var dataSource = (BindingList<MyEntity>)dataGridView1.DataSource;
                dataSource.Remove(itemToDelete);
            }
        }
    }
Sign up to request clarification or add additional context in comments.

1 Comment

note, that if you're using DataTable as the data source (I've read your comment), then the DataBoundItem is the DataRow, and the solution even simpler (you don't need any entity type). Just get the id value from the DataRow instance. And if you use DataAdapter, then you even don't need DataBoundItem. Just remove row from data table, and call DataAdapter.Update(DataTable).
0

Try it in this way Follow the following steps
1. Delete your row from DataBase
2. Clear Datasource of Your DataGridview
3. Select data from Database and set it to DataGridview

Comments

0

"Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index"

It means that you are accessing a location or index which is not present in collection. When you click the delete button, verify whether any cell is selected.

if(dataGridView1.SelectedCells.Count > 0)
{ 
   i = dataGridView1.SelectedCells[0] 
   OleDbConnection con = new OleDbConnection(constr);  
   OleDbCommand delcmd = new OleDbCommand();
   if (dataGridView1.Rows.Count > 1 && i != dataGridView1.Rows.Count - 1)
   {
       delcmd.CommandText = "DELETE FROM tb1 WHERE ID=" + dataGridView1.SelectedRows[i].Cells[0].Value.ToString() + "";
       con.Open();
       delcmd.Connection = con;
       delcmd.ExecuteNonQuery();
       con.Close();
       dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[i].Index);
       MessageBox.Show("Row Deleted");
   }
}
else 
{
  MessageBox.Show("Please select a row");
}

3 Comments

i am showing data in datagridview like this... OleDbDataAdapter da = new OleDbDataAdapter("select * from tb1", con); DataTable dt = new DataTable(); da.Fill(dt); dataGridView1.DataSource = dt; is this the right way ??
i used your code..it is saying that i does not exist in the current context
Can you provide more clear picture where the "does not exist in the current context" message is displayed?
0
    private void btn_Click(object sender, EventArgs e)
    {
        foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)
        {
            using (MySqlConnection con = new MySqlConnection(cs))
            {
                MySqlCommand cmd = con.CreateCommand();
                int id =Convert.ToInt32(dataGridView1.SelectedRows[0].Cells[0].Value);
                cmd.CommandText = "Delete from user where id='" + id+ "'";

                dataGridView1.Rows.RemoveAt(this.dataGridView1.SelectedRows[0].Index);
                con.Open();
                cmd.ExecuteNonQuery();

            }

        }
    }

1 Comment

To improve your answer you should add some basic explanation. At least what you changed in the code and preferably why you changed it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.