[英]how to delete records from database in c#
這是我的代碼:
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();
}
我無法理解我的代碼錯在哪里。 到達Device_Info_Obj.DevicesName.Remove(index, index);
時,編譯器出錯了Device_Info_Obj.DevicesName.Remove(index, index);
。 我該如何解決? 我想刪除數據庫中的選定行。
這個問題已經很模糊了,但是你命名對象的方式並沒有讓它變得更好。
我假設E_Shop_DB_Obj是您的數據庫上下文。 您想要從表DevicesInfo_Tbl中刪除一個對象。 看起來,DevicesName是表中的字段(字符串類型)。
你現在正在做的是從字段(字符串類型)Device_Info_Obj.DevicesName中刪除字符。 由於您創建了Device_Info_Obj,因此似乎DevicesName為null。 這就是你得到NullReference異常的原因。
無論如何,要刪除對象,您需要從上下文中刪除對象:
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();
}
您必須先找到具有鍵值的對象,然后才能將其刪除
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.