1

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.

Dovydas Šopa
  • 2,282
  • 8
  • 26
  • 34
Mamad Farrahi
  • 394
  • 1
  • 5
  • 20
  • What is the error? – Forklift Feb 09 '17 at 20:25
  • @Forklift An unhandled exception of type 'System.NullReferenceException' occurred in Project1.exe Additional information: Object reference not set to an instance of an object. – Mamad Farrahi Feb 09 '17 at 20:26
  • In your DevicesInfoObj constructor, you need to instantiate DevicesName. Either that or your DeviceInfoObj object is null. Debugging should show you which is the issue. – Forklift Feb 09 '17 at 20:29
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – T.S. Feb 09 '17 at 20:40
  • So, why don't you set `debug-exceptions` to `throw` and then just run your code? It will show where the issue – T.S. Feb 09 '17 at 20:41
  • @T.S. Please tell me a way that delete a row in sql server DB – Mamad Farrahi Feb 09 '17 at 21:55
  • `DELETE FROM [schema].[table] WHERE [column] = `. Do you realize that we can't help you because your question is vague? – T.S. Feb 09 '17 at 22:10

2 Answers2

2

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();
        }
1

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();
Hemal
  • 3,682
  • 1
  • 23
  • 54