使用C#以窗口形式验证组合框项目 [英] Validate combobox items in window form using C#

查看:73
本文介绍了使用C#以窗口形式验证组合框项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

i am using window forms in .net framework.i using c# language and sql server 2012.

i have a combobox on my window form.i am using parameterized query to insert the items from the combobox.i want to validate my control. if i do not select any items so message box should be display "Please select the item" or if i select the items so that item which i have selected in the combobox should be insert into my database table . i have tried my codes are blow. but i got one error message "Must declare the scalar variable "@ProductCategory"."





我尝试过:



if(comboproductcategory.SelectedIndex< 0)

{

MessageBox.Show(请选择项目);

}

else

{



cmd.Parameters.AddWithValue(@ ProductCategory,comboproductcategory.SelectedItem);

}



What I have tried:

if (comboproductcategory.SelectedIndex < 0)
{
MessageBox.Show("Please select the item");
}
else
{

cmd.Parameters.AddWithValue("@ProductCategory", comboproductcategory.SelectedItem);
}

推荐答案

你的避风港没有显示周围的代码,但我猜它看起来像这样:

You haven't shown the surrounding code, but I'm guessing it looks something like this:
using (var conn = new SqlConnection("..."))
using (var cmd = new SqlCommand("INSERT INTO SomeTable (SomeColumns) VALUES (@ProductCategory)"))
{
    if (comboproductcategory.SelectedIndex < 0)
    {
        MessageBox.Show("Please select the item");
    }
    else
    {
        cmd.Parameters.AddWithValue("@ProductCategory", comboproductcategory.SelectedItem);
    } 
    
    conn.Open();
    cmd.ExecuteNonQuery();
}



细节可能略有不同,但关键是你仍在尝试执行命令,即使没有选择任何项目。



您需要先验证表格,并且只有在选择了项目时才执行命令:


The details might be slightly different, but the key point is that you are still trying to execute the command, even if there is no item selected.

You need to validate the form first, and only execute the command if there is an item selected:

if (comboproductcategory.SelectedIndex < 0)
{
    MessageBox.Show("Please select the item");
    return;
}

using (var conn = new SqlConnection("..."))
using (var cmd = new SqlCommand("INSERT INTO SomeTable (SomeColumns) VALUES (@ProductCategory)"))
{
    cmd.Parameters.AddWithValue("@ProductCategory", comboproductcategory.SelectedItem);
    
    conn.Open();
    cmd.ExecuteNonQuery();
}



如果验证失败,您可以从方法返回返回,或移动整个连接和命令块进入 else 块。


You can either return from the method if the validation fails, or move the entire connection and command block into the else block.


这篇关于使用C#以窗口形式验证组合框项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆