为什么没有在访问数据库中插入Integer值

时间:2016-07-31 07:17:20

标签: c# datagridview ms-access-2007

Iam尝试将整数值插入到Access数据库中,但是它给我的Object不能从DBNull转换为其他类型。错误,但在datagridview我提出一个值,但仍然显示这个错误

--> NC1 --> VC1 --modal-> NC2 --> VC2 --show-> VC3    (NC = UINavigationController,
             ^                                  |      VC = UIViewController)
             |                                  |
             ----Segue I'm trying to achieve-----

graphic

2 个答案:

答案 0 :(得分:0)

"铅笔"表示正在编辑行,因此 - 即使输入的值为2 - Availability 的值也很可能为空。

所以你的概念似乎有缺陷;当dataGridView1.IsCurrentRowDirty true false 时,您不应尝试插入数据。

答案 1 :(得分:0)

终于得到了一个解决方案,我将我的代码dataGridView1_RowLeave更改为dataGridView1_CellValueChanged并且工作正常

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
med_id = dataGridView1.Rows[e.RowIndex].Cells["Med_id"].Value.ToString();

if (med_id == "")
{
med_id1 = 0;
}
else
{
med_id1 = Convert.ToInt32( dataGridView1.Rows[e.RowIndex].Cells["Med_id"].Value.ToString());

}
if (med_id1 == 0)
{
try
{
string Medicine_Name = dataGridView1.Rows[e.RowIndex].Cells["Medicine_Name"].Value.ToString();
string Dealer_name = dataGridView1.Rows[e.RowIndex].Cells["Dealer_name"].Value.ToString();
int Availability = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["Availability"].Value.ToString());
string cmd1 = "insert into Medicine_Available_Detail(Medicine_Name,Dealer_name,Availability) values(@Medicine_Name,@Dealer_name,@Availability)";
OleDbCommand cmd = new OleDbCommand(cmd1, con);

cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@Medicine_Name", Medicine_Name);
cmd.Parameters.AddWithValue("@Dealer_name", Dealer_name);
cmd.Parameters.AddWithValue("@Availability", Availability);
con.Open();
int n = cmd.ExecuteNonQuery();
con.Close();
if (n > 0)
{

MessageBox.Show("Data Inserted Successfully", "Data Inserted ", MessageBoxButtons.OK, MessageBoxIcon.Information);


}
Load_data();
dataGridView1.Refresh();
}
catch (Exception ex)
{

}


}
else
{
string Medicine_Name = dataGridView1.Rows[e.RowIndex].Cells["Medicine_Name"].Value.ToString();
string Dealer_name = dataGridView1.Rows[e.RowIndex].Cells["Dealer_name"].Value.ToString();
int Availability = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["Availability"].Value.ToString());
cmd = new OleDbCommand();

cmd.CommandType = CommandType.Text;
cmd = con.CreateCommand();
cmd.CommandText = "update Medicine_Available_Detail set Medicine_Name='" + dataGridView1.Rows[e.RowIndex].Cells["Medicine_Name"].Value.ToString() + "',Dealer_name='" + dataGridView1.Rows[e.RowIndex].Cells["Dealer_name"].Value.ToString() + "',Availability='" + Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["Availability"].Value.ToString())+ "'where Med_id=" + med_id1 + "";
con.Open();
int n = cmd.ExecuteNonQuery();
con.Close();
if (n > 0)
{

MessageBox.Show("Data Updated Successfully", "Data Inserted ", MessageBoxButtons.OK, MessageBoxIcon.Information);


}
Load_data();
dataGridView1.Refresh();

}
}