Mamad Farrahi
Mamad Farrahi

Reputation: 494

how to delete records from database in c#

This is my code:

private void button1_Click(object sender, EventArgs e){
    int index = dataGridView1.CurrentCell.RowIndex;

    Model1.DevicesInfo_Tbl Device_Info_Obj = new Model1.DevicesInfo_Tbl();

    Device_Info_Obj.DevicesName.Remove(index, index);

    E_Shop_DB_Obj.SaveChanges();
    dataGridView1.Refresh();
}

I can't understand where my code is wrong. Compiler got an error when arrive to Device_Info_Obj.DevicesName.Remove(index, index);. How can i fix it? I want to delete selected row in Data Base.

Upvotes: 1

Views: 353

Answers (2)

Hemal
Hemal

Reputation: 3760

You have to first find the object with a key value and then you can remove it

var item = E_Shop_DB_Obj.DevicesInfo_Tbl.Find(index);//ASSUMING index IS THE KEY
E_Shop_DB_Obj.DevicesInfo_Tbl.Remove(item);
E_Shop_DB_Obj.SaveChanges();

Upvotes: 1

user4864425
user4864425

Reputation:

This question is already vague, but the way you name the objects doesn't make it better.

I assume that E_Shop_DB_Obj is your database context. You want to remove an object from table DevicesInfo_Tbl. And it looks like DevicesName is a field (of type string) in your table.

What you are doing now is removing characters from the field (of type string) Device_Info_Obj.DevicesName. Since you created Device_Info_Obj it seems that DevicesName is null. That is why you get the NullReference exception.

Anyway, to delete an object you'll need to remove the object from the context:

        using (var E_Shop_DB_Obj = new Model())
        {
            var item = E_Shop_DB_Obj.DevicesInfo_Tbl.FirstOrDefault(a => a.Id == index);
            // Test if item is not null
            E_Shop_DB_Obj.DevicesInfo_Tbl.Remove(item);
            E_Shop_DB_Obj.SaveChanges();
        }

Upvotes: 2

Related Questions