I am trying to insert data from dgv to sql as per below.
The above transaction shows that the column “Amount1 “ rows “1” has Null value where as same column’s rows “2” has value. I wants to insert the multiple records into table. The above transaction is sample.
I am trying to insert it from below which is fail to insert.
how to solve it?.
Code:
TransID Amount Amount1 ------------------------------------------------- 1 12000.00 1 12000.00
I am trying to insert it from below which is fail to insert.
Code:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if ((Keys)e.KeyChar == Keys.Enter)
{
string mess = "Confirm";
string cap = "Wanna Save";
MessageBoxButtons bt = MessageBoxButtons.YesNo;
DialogResult result;
result = MessageBox.Show(mess, cap, bt);
if (result == DialogResult.Yes)
{
string connstr = "server=.;initial catalog=maa;uid=mah;pwd=mah";
SqlConnection con = new SqlConnection(connstr);
con.Open();
for (int i = 0; i < dataGridView1.Rows.Count-1; i++)
{
decimal? amt = null;
decimal? amt1 = null;
amt = Convert.ToDecimal(dataGridView1.Rows[i].Cells[0].Value.ToString());
amt1 = Convert.ToDecimal(dataGridView1.Rows[i].Cells[1].Value.ToString());// try to casting null but fail
if (amt.HasValue || amt1.HasValue)
{
string sql = " insert into dummy(amount,amount1) values (@amount,@amount1)";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("@amount", SqlDbType.Decimal).Value = amt;
cmd.Parameters.Add("@amount1", SqlDbType.Decimal).Value = amt1;
if (amt == null || amt1 == null)
{
cmd.Parameters.Add("@amount", SqlDbType.Decimal).Value = DBNull.Value;
cmd.Parameters.Add("@amount1", SqlDbType.Decimal).Value = DBNull.Value;
}
cmd.ExecuteNonQuery();
amt = null;
amt1 = null;
}
}
}
}
}
Comment