0

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

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? I tried to make the year optional, by inputting a default value to my Year parameter:

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#? 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]. 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. 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

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

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'

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 :)

Community
  • 1
  • 1

2 Answers2

0

Use the int.TryParse method to check if the year is a real number like this

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
}
0

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. TryParse returns bool which means that conversion is succeful (value true) or not (value false). Integer value is in out variable. 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. Or, edit your original question.

EDIT:

To insert null or nothing into database if year == 0, you can pass parameters like this:

if (year != 0)
    cmd.Parameters.AddWithValue("@year", year);
else
    cmd.Parameters.AddWithValue("@year", DBNull.Value);
Nino
  • 6,931
  • 2
  • 27
  • 42
  • I see. I was using the int.TryParse wrong, that makes sense now and I got it to work. Thanks a lot :). Quick question though, can I set the year to be an empty string? So in my database, under "year" it would just be empty instead of showing "0"? – Kevin Matthews May 17 '17 at 12:12
  • I have edited my answer. Btw, to say "thanks" you can mark my answer as solution ;) – Nino May 17 '17 at 13:50
  • Ahh yes, sorry. I was working on some other stuff in the meantime and forgot :) Thanks again! – Kevin Matthews May 17 '17 at 14:45