c# - 如何使用数据库列的值检查组合框的文本

标签 c# sql-server winforms combobox

我是编程新手,这可能是一项简单的任务,但我面临着困难。

我在 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/

相关文章:

sql - 如何删除/重命名 SQL 中的重复列(非重复行)

sql - 不使用任何聚合函数计算行数

c# - 如果 TextBox 为空或已经为 0,如何禁止用户在 TextBox 上插入 0?

java : use of executeQuery(string) method not supported error?

wpf - 如何默认关闭群组?

c# - 如何使我的表单透明,但我在上面绘制的内容却不透明?

c# - 总是 try catch 外部资源调用?

c# - "SocketException: Name or service not known"当 URL 在浏览器中正常加载时

c# - Win32_NetworkAdapter 查询中的网络地址始终为空

c# - 林克 2 SQL : update record via a web service