简体   繁体   English

c#注册表格:可选文本框

[英]c# Register form: Optional text boxes

I'm working on a project which requires a Register option. 我正在一个需要注册选项的项目中。 I have already created a form that a user can fill out and it successfully saves to the database, if every text box has been filled out. 我已经创建了一个表单,供用户填写,如果每个文本框均已填写,则该表单可以成功保存到数据库中。 I need to have some of them be optional. 我需要其中一些是可选的。

private void button1_Click(object sender, EventArgs e)
    {

        Registercar(textBox1.Text, textBox2.Text, Convert.ToInt32(textBox3.Text));
    }

    private static void Registercar(string make, string model, int year)
    {
        var con = GetConnection();
        try
        {
            MySqlCommand cmd = new MySqlCommand();
            cmd.Connection = con;
            cmd.CommandText = "INSERT INTO user_car (ID,make,model,year) VALUE (@ID, @make, @model, @year)";
            cmd.Prepare();
            cmd.Parameters.AddWithValue("@ID", 0);
            cmd.Parameters.AddWithValue("@make", make);
            cmd.Parameters.AddWithValue("@model", model);
            cmd.Parameters.AddWithValue("@year", year);
            cmd.ExecuteNonQuery();
            if (con !=null) { con.Close(); };

            MessageBox.Show("Car successfully registered");
        }
        catch (Exception ex)
        {
            MessageBox.Show(Convert.ToString(ex));
        }
        finally
        {
            con.Close();
        }
    }

The code above is the part of the register, where the user has the option to register a car that will be tied to their account. 上面的代码是注册的一部分,用户可以选择注册与自己的帐户相关联的汽车。 If they choose the add a car, they need to input the Make and the Model, while the Year is optional. 如果选择添加汽车,则需要输入品牌和型号,而年份是可选的。 If they input all the information, it successfully saves the information into the database. 如果他们输入了所有信息,它将成功地将信息保存到数据库中。

However, If I try to leave the Year option blank, I get the following error: "An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll 但是,如果我尝试将Year选项保留为空白,则会出现以下错误:“ mscorlib.dll中发生了'System.FormatException'类型的未处理异常

Additional information: Input string was not in a correct format." 其他信息:输入字符串的格式不正确。”

This tells me that I am most likely not allowed to leave it blank. 这告诉我,很可能不允许我将其留空。 I tried to figure out different options where I could leave it blank, and still save the other information into the database. 我试图找出其他选项,可以将其留空,而仍将其他信息保存到数据库中。 The first option I tried came from this post: How can we declare Optional Parameters in C#.net? 我尝试的第一个选项来自这篇文章: 我们如何在C#.net中声明可选参数? I tried to make the year optional, by inputting a default value to my Year parameter: 我试图通过向Year参数输入默认值来使year为可选:

private static void Registercar(string make, string model, int year = 0)

However I still get the same error as before. 但是我仍然得到和以前一样的错误。 The next option I tried came from this post: How can you use optional parameters in C#? 我尝试的下一个选项来自这篇文章: 如何在C#中使用可选参数? The first answer was the same as the previous one, set the parameter to a set value. 第一个答案与前一个答案相同,将参数设置为设定值。 Another answer further down suggested to use "System.Runtime.InteropServices" and set the parameter to [Optional]. 进一步的答案是建议使用“ System.Runtime.InteropServices”并将参数设置为[Optional]。 I tried, but I get the same error as before. 我尝试过,但收到的错误与以前相同。 I figured it had to do with the fact that I try to convert and empty string to an int. 我认为这与我尝试将字符串转换为空并转换为int有关。 A quick search led me to this post: Convert string to integer Here I am told I can try to use int.Parse, so I set it up like this 快速搜索将我带到了这篇文章: 将字符串转换为整数在这里,我被告知可以尝试使用int.Parse,因此我将其设置为

private void button1_Click(object sender, EventArgs e)
    {
        int year = int.Parse(textBox3.Text.Trim());
        Registercar(textBox1.Text, textBox2.Text, year);

    }

Same error as before. 与以前相同的错误。 Next I tried the "Int32.TryParse()" which checks if the string contains an int, if not, output an integer value 接下来,我尝试了“ Int32.TryParse()”,它检查字符串是否包含int,如果不包含,则输出整数值

private void button1_Click(object sender, EventArgs e)
    {
        int year;
        string str = textBox3.Text.Trim();
        Registercar(textBox1.Text, textBox2.Text, Int32.TryParse(str, out year);

    }

Now it tells me I can't convert from 'bool' to 'int' 现在它告诉我我不能从'bool'转换为'int'

At this point I have pretty much almost given up. 在这一点上,我几乎已经放弃了。

The thing that works currently, is that if every box is filled out, it successfully saves the information to the database. 当前有效的是,如果每个框都填写完毕,它将成功地将信息保存到数据库中。 However, I need some of the text boxes to be optional, and I can't get that to work. 但是,我需要一些文本框是可选的,而我无法使其正常工作。

I'm sorry for the long post. 很长的帖子对不起。 I hope someone is able to help or come with a suggestion :) 我希望有人能够提供帮助或提出建议:)

Use the int.TryParse method to check if the year is a real number like this 使用int.TryParse方法检查年份是否为像这样的实数

int nYear=0;
if(int.TryParse(txtYear.Text, out nYear)
{
    //the value is a number
    //Also the nYear vairable has the numeric integer value
    //    you can use it
}
else
{
    //The value isn't a number
}

Correct me if I'm wrong, but I think your only problem i converting text to string. 如果我错了,请纠正我,但是我认为您唯一的问题就是将文本转换为字符串。 Making some parameter optional isn't really necessary here. 此处实际上并不需要将某些参数设置为可选。

int.TryParse() is a way to go, but you're using it wrong. int.TryParse()是一种解决方法,但是使用错误。 TryParse returns bool which means that conversion is succeful (value true ) or not (value false ). TryParse返回bool ,表示转换成功(值为true )或不成功(值为false )。 Integer value is in out variable. 整数值是在out可变的。 So, to use it in your case, try something like this: 因此,要在您的情况下使用它,请尝试以下操作:

private void button1_Click(object sender, EventArgs e)
{
    int year;
    string str = textBox3.Text.Trim();
    //if parsing isn't successful, year will be set as 0
    if (!int.TryParse(str, out year))
    {
        //notice user that that isn't correct value for year
        year = 0;
    }
    //no need for else, year now contains int value but beware, it can be value from 0  to 2147483647

    Registercar(textBox1.Text, textBox2.Text, year));

}

if you have additional questions about "optional" parameters or additional handling of that year value, feel free to ask. 如果您对“可选”参数或该year价值的其他处理有其他疑问,请随时提出。 Or, edit your original question. 或者,编辑您的原始问题。

EDIT: 编辑:

To insert null or nothing into database if year == 0, you can pass parameters like this: 要在year == 0时向数据库中插入nullnothing插入,可以传递如下参数:

if (year != 0)
    cmd.Parameters.AddWithValue("@year", year);
else
    cmd.Parameters.AddWithValue("@year", DBNull.Value);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM