我是编程新手,这可能是一项简单的任务,但我面临着困难。
我在 Windows 窗体中有一个组合框,它与 SQL Server 中名为 id
的表列链接。我想检查组合框中输入的值是否存在于列中。如果是,则进一步工作,如果不是,则向用户发送错误消息,无论用户按 Enter、Tab 还是 Selection changed,它都应该起作用。
填充组合框的代码
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");
}
最佳答案
这可能是适合您的解决方案。
首先,获取最近选择的组合框值。
然后,假设您使用的是 EF,检查带有组合框所选 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.")
}
}
关于c# - 如何使用数据库列的值检查组合框的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42920250/