[英]Inserting Datagridview rows into database using Entity Framework
如果我想向datagridview添加記錄,沒關系,但是我想向數據庫中添加datagridview中的哪些行的記錄。
有一種方法 - 我如何添加 Datagridview行。
public void SepeteEkle()
{
decimal? tutar;
decimal? toplamtutar = 0;
int miktarsum = 0;
DataRow urun = dt.NewRow();
tutar = Convert.ToDecimal(lblFiyat.Text) * Convert.ToInt32(txtMiktar.Text);
bool itemfound = false;
for (int i = 0; i < dgvSepet.Rows.Count; i++)
{
if (Convert.ToString(dgvSepet.Rows[i].Cells[0].Value) == lblStokID.Text)
{
miktarsum += Convert.ToInt32(dgvSepet.Rows[i].Cells[4].Value) + Convert.ToInt32(txtMiktar.Text);
toplamtutar += Convert.ToDecimal(dgvSepet.Rows[i].Cells[5].Value) + tutar;
dgvSepet.Rows[i].Cells[4].Value = miktarsum;
dgvSepet.Rows[i].Cells[5].Value = toplamtutar;
itemfound = true;
}
}
if (itemfound == false)
{
urun["Id"] = lblStokID.Text;
urun["StokKodu"] = txtStokKodu.Text;
urun["Ürün"] = txtStokAdi.Text;
urun["Fiyat"] = lblFiyat.Text;
urun["Miktar"] = txtMiktar.Text;
urun["Toplam"] = tutar;
dt.Rows.Add(urun);
dgvSepet.DataSource = dt;
}
}
我想使用 Entity Framework 將所有創建的行添加到數據庫中。
我嘗試了什么:
public void DatabaseSepetAktar()
{
xstHar stokHareketModel = new xstHar();
stokHareketModel.stharCariKod = txtCariKodu.Text;
stokHareketModel.stharTarih = DateTime.Now;
stokHareketModel.stharDovFiyat = Convert.ToDecimal(lblTotal.Text);
for (int i = 0; i < dgvSepet.Rows.Count -1 ; i++)
{
stokHareketModel.masterId = Convert.ToInt32(dgvSepet.Rows[i].Cells[0].Value);
stokHareketModel.stokKodu = dgvSepet.Rows[i].Cells[1].Value.ToString();
stokHareketModel.stharGcMik1 = Convert.ToDecimal(dgvSepet.Rows[i].Cells[4].Value);
using (fastCellDb db = new fastCellDb())
{
db.xstHars.Add(stokHareketModel);
db.SaveChanges();
}
}
}
但我得到一個錯誤
驗證異常
來自實體框架。
我怎么解決這個問題?
當您嘗試轉換具有錯誤類型的值時會引發驗證異常,這是由於錯誤的索引。 當您使用文本索引向 DataGridView dt.Rows.Add(urun)
添加一行時,將索引方式從數字更改為文本:Cells[0] → Cells["Id"] 等。
看看這條線: for (int i = 0; i < dgvSepet.Rows.Count -1; i++)
,似乎 -1 在那里多余。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.