gpt4 book ai didi

c# - 无法使用 c# 在 winform 中使用空 ValueMember 在 ListControl 中设置 SelectedValue

转载 作者:太空狗 更新时间:2023-10-30 01:01:17 29 4
gpt4 key购买 nike

我有一个从数据库加载数据的组合框,但我得到一个错误,你不能在 ListControl 中设置 selectedValue 尽管我已经将 selectValue 设置为表的主键。但是在运行时仍然出错..这是代码..

    private void FormAddStudent_Load(object sender, EventArgs e)
{
//For combobox Campuse
cBoxCampus.DataSource = GetAllCampuses();

cBoxCampus.DisplayMember = "campus_name";
cBoxCampus.SelectedValue = "campus_id";
//Foe ComboBox Department
cBoxDepartment.DataSource = GetAllDepartment();

cBoxDepartment.DisplayMember = "depname";
cBoxDepartment.SelectedValue = "depid";
}

这是插入按钮背后的代码

        private void btnInsert_Click(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["UMSdbConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT ISNULL(MAX(std_id),0)+1 FROM Student", con);
cmd.CommandType = CommandType.Text;
tbID.Text = cmd.ExecuteScalar().ToString();

{

using (SqlCommand cmd1 = new SqlCommand("INSERT INTO Student (std_id,std_name,std_f_name,std_mob,std_gender,std_cnic,std_campus,std_dep,std_address,std_batch,std_batch_year)VALUES(@std_id,@std_name,@std_f_name,@std_mob,@std_gender,@std_cnic,@std_campus,@std_dep,@std_address,@std_batch,@std_batch_year)VALUES(@campus_id,@campus_name)", con))
{

cmd1.CommandType = CommandType.Text;
cmd1.Parameters.AddWithValue("@std_id", tbID.Text);
cmd1.Parameters.AddWithValue("@std_name", tbName.Text);
cmd1.Parameters.AddWithValue("@std_f_name", tbFatherName.Text);
cmd1.Parameters.AddWithValue("@std_mob", tbMobNumber.Text);
cmd1.Parameters.AddWithValue("@std_gender", GetGender());
cmd1.Parameters.AddWithValue("@std_cnic", tbMobNumber.Text);
cmd1.Parameters.AddWithValue("@std_campus",(cBoxCampus.SelectedIndex == -1) ? 0: cBoxCampus.SelectedValue);
cmd1.Parameters.AddWithValue("@std_dep", (cBoxDepartment.SelectedIndex == -1) ? 0 : cBoxDepartment.SelectedValue);
cmd1.Parameters.AddWithValue("@std_address", tbAddress.Text);
cmd1.Parameters.AddWithValue("@std_batch", tbBatchNo.Text);
cmd1.Parameters.AddWithValue("@std_batch_year", tbBatchYear.Text);
cmd1.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Saved");

}
}


}
}

最佳答案

替换

cBoxCampus.SelectedValue = "campus_id";

ListControl.ValueMember属性

cBoxCampus.ValueMember = "campus_id";

cBoxDepartment做类似的操作

关于c# - 无法使用 c# 在 winform 中使用空 ValueMember 在 ListControl 中设置 SelectedValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40239494/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com