I am adding multiple data through my datagridview named 'dgv'. And I want save multiple data to my entities 'de' and database tabel 'DetailSPH2'.
But, when I save multiple data with "de.SaveChanges();" , It didn't work. only one row in datagridview is being saved.
I already linq code below.
How to save all rows in my datagridview?
Please help me.
for (int i = 0; i < dgv.RowCount; i++)
{
string KodeBarang = dgv.Rows[dgv.CurrentRow.Index].Cells[0].Value.ToString();
string NamaBarang = dgv.Rows[dgv.CurrentRow.Index].Cells[1].Value.ToString();
string Harga = dgv.Rows[dgv.CurrentRow.Index].Cells[2].Value.ToString();
string JumlahPesananSPH = dgv.Rows[dgv.CurrentRow.Index].Cells[3].Value.ToString();
string TotalPerBarang = dgv.Rows[dgv.CurrentRow.Index].Cells[4].Value.ToString();
DetailSPH2 la = new DetailSPH2();
la.NoSPH = txtNoSPH.Text;
la.KodeBarang = KodeBarang;
la.NamaBarang = NamaBarang;
la.Harga = float.Parse(Harga);
la.JumlahPesananSPH = int.Parse(JumlahPesananSPH);
la.TotalPerBarang = float.Parse(TotalPerBarang);
de.AddToDetailSPH2(la);
de.SaveChanges();
}
With this line (and the following ones)
string KodeBarang = dgv.Rows[dgv.CurrentRow.Index].Cells[0].Value.ToString();
you take always the same CurrentRow
and your loop repeats the insert with the same values.
You need to take the Row
indexed by your loop variable i
string KodeBarang = dgv.Rows[i].Cells[0].Value.ToString();
and so on for the other variables
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.