C# 如何使用数据库列的值检查组合框的文本
我是编程新手,这可能是一项简单的任务,但我面临着困难 我在Windows窗体中有一个组合框,它与SQL Server中名为id的表列链接。我想检查在组合框中输入的值是否存在于列中。如果是,则继续工作;如果不是,则向用户发送错误消息,无论用户是否按Enter键、Tab键或选择是否更改,都应该工作 用于填充组合框的代码C# 如何使用数据库列的值检查组合框的文本,c#,sql-server,winforms,combobox,C#,Sql Server,Winforms,Combobox,我是编程新手,这可能是一项简单的任务,但我面临着困难 我在Windows窗体中有一个组合框,它与SQL Server中名为id的表列链接。我想检查在组合框中输入的值是否存在于列中。如果是,则继续工作;如果不是,则向用户发送错误消息,无论用户是否按Enter键、Tab键或选择是否更改,都应该工作 用于填充组合框的代码 sqlCmd.Connection = con; sqlCmd.CommandType = CommandType.Text; s
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "SELECT pid FROM report2";
System.Data.SqlClient.SqlDataAdapter sqlDataAdap = new
System.Data.SqlClient.SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
comboBox1.DataSource = dtRecord;
comboBox1.ValueMember = "pid";
con.Close();
***id是字母数字的
提前谢谢
到目前为止,我已经这样做了,但我得到了错误消息,为所有多次计时,即使他们是匹配的项目列表中的值
for (int i = 0; i <= comboBox1.Items.Count-1; i++)
{
if (comboBox1.Text.Equals(comboBox1.GetItemText(comboBox1.Items[i]).ToString()))
{
con.Open();
string sql = "SELECT * FROM report2 where partno='" + comboBox1.Text + "'";
System.Data.SqlClient.SqlDataAdapter dataadapter = new System.Data.SqlClient.SqlDataAdapter(sql, con);
DataSet ds = new DataSet();
dataadapter.Fill(ds, "report2");
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "report2";
dataGridView1.ReadOnly = false;
con.Close();
}
else
{
MessageBox.Show("enter valid value for for loop");
}
这可能是你的解决办法 首先,获取最近选择的combobox值 然后,假设您使用的是EF,请检查选择了combobox id的数据库 最后,如果表中没有这样的id,则显示消息而不执行任何操作,或者如果表中有这样的id,则继续使用您的逻辑
private void yourCombobox_SelectedValueChanged(object sender, EventArgs e){
int selectedComboboxId = yourCombobox.SelectedValue;
bool recordExists = _context.Set<YourEntity>().Any(x=>x.Id = selectedComboboxId);
if(recordExists){
//record is in the table
//your code
}
else
{
//record is not in the table
MessageBox.Show("Record does not exist. Select new option.")
}
}
您可以将组合框设置为dropdownlist。这将限制用户在组合框中输入任何新值,因此您不需要向用户显示错误消息
试试下面
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "SELECT pid FROM report2";
System.Data.SqlClient.SqlDataAdapter sqlDataAdap = new
System.Data.SqlClient.SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
comboBox1.DropDownStyle = ComboBoxStyle.DropDownList; //this statement added
comboBox1.DataSource = dtRecord;
comboBox1.ValueMember = "pid";
con.Close();
请发布您迄今为止尝试过的代码。请向我们展示一些代码。如何保存列值?是列表/数组/字典吗?@mukul,我已经更新了我的问题。希望你现在能理解。如果有任何疑问,请告诉我。谢谢..实体框架_context是一个DbSet,但是这一行可以替换为SqlCommand,谢谢,但是列表太长了,所以这将不起作用,您查看了链接了吗-