Atul
Atul

Reputation: 155

Delete command give error

Wherever I try to delete my datagridview row its giving me

datagridview index was out of range. must be non-negative and less than the size of the collection. parameter name: index exception

and I have one last column name is balance. At footer its show me total values but the problem is its not showing me last balance value.

Suppose I am entering three values balance -2000, 3000, 4000 so its shows me only 2000+3000 sum its not showing last row sum.

I am pasting that code also

delete code :

private void btndelete_Click(object sender, EventArgs e)
{
    if (dataGridView1.SelectedCells.Count > 0)
    {

        **if (dataGridView1.Rows.Count > 1 && dataGridView1.SelectedRows[0].Index != dataGridView1.Rows.Count - 1 )**//Exception coming this line 
        {
            cmd.CommandText = "Delete from Ledger where AccountNumber=" + dataGridView1.SelectedRows[0].Cells[0].Value.ToString() + "";
            con.Open();
            cmd.Connection = con;
            cmd.ExecuteNonQuery();
            con.Close();
            dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
            MessageBox.Show("Row Deleted");
            Load_data();
        }
        else
        {
            MessageBox.Show("Please select a row");
        }

    }

}

total sum code:

private void dataGridView1_DataSourceChanged(object sender, EventArgs e)
{
    double Total = 0;
    for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
    {
        Total += Convert.ToDouble(dataGridView1.Rows[i].Cells["Balance"].Value);
    }
    dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells["Balance"].Value = Total;
    lblsum.Text =Convert.ToString(Total);


}

enter image description here

Upvotes: 1

Views: 67

Answers (1)

Steve
Steve

Reputation: 216293

SelectedRows and Rows are two different collection.
Having Rows > 1 doensn't mean SelectedRows > 0

If I understand your code your intention is to delete a row from the grid but not if the selected row is the last one in the grid (where you keep the summary)

if (dataGridView1.Rows.Count > 1 && 
    dataGridView1.SelectedRows.Count > 0 && 
    dataGridView1.SelectedRows[0].Index != dataGridView1.Rows.Count - 1 ) 

To fix your sum, you need to simply change you loop to

for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)

Notice that your actual code loops until the indexer is LOWER than Rows.Count - 2 but this is wrong because it excludes that last good row being the Footer at Rows.Count - 1

A part from this, I strongly suggest you to not have global objects for the OleDbCommand and the OleDbConnection. It is good practice to create them at the point where you need them and destroy them immediately after usage. This avoid keeping precious resources locked and subtle bugs with not initialized objects or with remnants of previous code paths

string cmdText = "DELETE from Ledger Where AccountNumber = @num";
using(OleDbConnection con = new OleDbConnection(......))
using(OleDbCommand cmd = new OleDbCommand(cmdText, con))
{
    con.Open();
    cmd.Parameters.Add("@num", OleDbType.Integer).Value =   
             Convert.ToInt32(dataGridView1.SelectedRows[0].Cells[0].Value);
    cmd.ExecuteNonQuery();
    dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
    MessageBox.Show("Row Deleted");
    Load_data();
}

Upvotes: 1

Related Questions