我在C#中的一个ComboBox中显示一个数据库的数据。
因此,我有一个数据库表,其中有一个id和名称。
现在我尝试在ComboBox中显示名称并使用id作为值。我知道还有一些其他的问题,但不幸的是,它并没有为我解决这个问题。
我现在使用的代码是这样的。
lblId.Visible = false;
txtId.Visible = false;
cbType.Items.Clear();
con.Open();
cmd = "SELECT Type_id, Type FROM type";
SqlDataAdapter da = new SqlDataAdapter(cmd, con);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
cbType.Items.Add(dr["Type_id"].ToString());
}
con.Close();
这里我只要求输入id,但我发现了这样的东西:
cbType.DataSource = dt;
cbType.DisplayMember = "Type";
cbType.ValueMember = "Type_id";
这样就可以显示名字了
但现在我需要把它插入到数据库中。为此我使用了下面的代码。
string klant = txtKlant.Text;
string kenteken = txtKenteken.Text;
string type = cbType.SelectedItem.ToString();
DateTime startdatum = dtpStartdatum.Value;
DateTime einddatum = dtpEinddatum.Value;
int result = 0;
con.Open();
cmd = "INSERT INTO reserveringen (Klant, Kenteken, Type_id, Startdatum, Einddatum) values(@Klant, @Kenteken, @Type_id, @Startdatum, @Einddatum)";
command = new SqlCommand(cmd, con);
command.Parameters.Add(new SqlParameter("@Klant", klant));
command.Parameters.Add(new SqlParameter("@Kenteken", kenteken));
command.Parameters.Add(new SqlParameter("@Type_id", type));
command.Parameters.Add(new SqlParameter("@Startdatum", startdatum));
command.Parameters.Add(new SqlParameter("@Einddatum", einddatum));
result = command.ExecuteNonQuery();
if (result > 0)
{
MessageBox.Show("De reservering is toegevoegd.");
txtKlant.Text = "";
txtKenteken.Text = "";
cbType.Items.Clear();
dtpStartdatum.Value = DateTime.Now;
dtpEinddatum.Value = DateTime.Now;
con.Close();
bekijkReserveringen();
}
else
{
MessageBox.Show("Er is iets misgegaan, de reservering is niet toegevoegd.");
con.Close();
}
但当我试图将它添加到数据库中时,我得到以下错误信息: result = command.ExecuteNonQuery();:将nvarchar值'System.Data.DataRowView'转换为数据类型int时,转换失败。
当我使用类型时,我说的是id的名字,因为它在数据库中是这样叫的。
如果我用第一个代码块插入它,它可以正常工作,但对于用户,我需要显示名称。
那么有人知道问题可能出在哪里吗?
先谢谢了!
使用 cbType.SelectedValue
而不是 SelectedItem
而你应该正确地得到这个值。