我有一个comboBox,其中数据从包含Id作为主键的表中加载,并且在Load事件中的comboBox内加载了唯一的名称和数据,现在当我尝试将数据插入表中时,它给了我问题中声明的异常和行中出现的异常:
cmd.ExecuteNonQuery();
我尝试了此链接中提供的解决方案,但它给了我相同的例外 ERROR : No mapping exists from object type System.Data.DataRowView to a known managed provider native type
这是我的加载事件代码:
try
{
if (cn.State == ConnectionState.Closed)
{
cn.Open();
}
SqlDataAdapter da = new SqlDataAdapter("select Id,name from carsCostsFor", cn);
DataTable dt = new DataTable();
da.Fill(dt);
carCostsCmbo.DataSource = dt;
carCostsCmbo.ValueMember = "Id";
carCostsCmbo.DisplayMember = "name";
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
这是保存按钮代码:
try
{
if (cn.State == ConnectionState.Closed)
{
cn.Open();
}
SqlCommand cmd = new SqlCommand("insert into carsCosts (Id,costId,costFor,costDate,costAmount,costNotes) values (@id,@cId,@for,@date,@amount,@notes)", cn);
cmd.Parameters.AddWithValue("@id", id);
cmd.Parameters.AddWithValue("@cId", carCostsCmbo.SelectedValue);
cmd.Parameters.AddWithValue("@for", carCostsCmbo.SelectedItem);
cmd.Parameters.AddWithValue("@date", carCostsDateDtp.Value);
cmd.Parameters.AddWithValue("@amount", carCostsAmountTxt.Text.Trim());
cmd.Parameters.AddWithValue("@notes", carCostsNotesRichTxt.Text.Trim());
cmd.ExecuteNonQuery();
MessageBox.Show("تم حفظ البيانات بنجاح");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}