0

Trying to add data to my database with these codes but keep getting an error, any advice to fix this? Object reference not set to an instance of an object.

private void button1_Click(object sender, EventArgs e)
        {
            con = new SqlConnection("Data Source=GREGJAMES\\SQLEXPRESS;Initial Catalog=Hotel;Integrated Security=True");
            con.Open();
            cmd = new SqlCommand("INSERT INTO [Guest Info] (Guest, Phone, TypeOfRoom, CheckIn, CheckOut, NumberOfAdults, NumberOfChildren) VALUES (@Guest, @Phone, @TypeOfRoom, @CheckIn, @CheckOut, @NumberOfAdults, @NumberOfChildren)", con);
            cmd.Parameters.Add("@Guest", textBox1.Text);
            cmd.Parameters.Add("@Phone", textBox1.Text);
            cmd.Parameters.Add("@TypeOfRoom", comboBox1.SelectedItem.ToString());
            cmd.Parameters.Add("@CheckIn", dateTimePicker1.Value.ToString());
            cmd.Parameters.Add("@CheckOut", dateTimePicker2.Value.ToString());
            cmd.Parameters.Add("@NumberOfAdults", comboBox2.SelectedItem.ToString());
            cmd.Parameters.Add("@NumberOfChildren", comboBox3.SelectedItem.ToString());
            cmd.ExecuteNonQuery();

            {
                MessageBox.Show("Reserved!");
            }
                this.Close();
Gonzo345
  • 943
  • 2
  • 16
  • 34
  • 1
    Welcome to StackOverflow. Have you debugged your code? Where does it throw the Exception? Have you looked into the StackTrace? – Gonzo345 May 07 '19 at 05:27
  • The error is on the line of cmd.Parameters.Add("@TypeOfRoom", comboBox1.SelectedItem.ToString()); – James Craig May 07 '19 at 05:31
  • Try to get the value from the ComboBox directly and check what that `ToString()` returns. Seems you're adding a `null` since maybe that ComboBox is null. It's even easier to debug and safer to do this way, instead of accessing directly to the control. – Gonzo345 May 07 '19 at 05:50
  • I'm so sorry but i have not a single idea how to do that. I'm very new to coding and my knowledge is basically just from watching videos online – James Craig May 07 '19 at 06:28
  • It would seem that there is no item selected in `comboBox1`. That is, `comboBox1.SelectedItem` is `null`. You can work around this using `comboBox1.SelectedItem?.ToString()`. – Peter van der Heijden May 07 '19 at 06:41

1 Answers1

0

Either the con or the cmd variable are null because the connection couldn't be made (these lines):

 con = new SqlConnection("Data Source=GREGJAMES\\SQLEXPRESS;Initial 
     Catalog=Hotel;Integrated Security=True");
 cmd = new SqlCommand("INSERT INTO [Guest Info] (Guest, Phone, TypeOfRoom, CheckIn, CheckOut, NumberOfAdults, NumberOfChildren) VALUES (@Guest, @Phone, @TypeOfRoom, @CheckIn, @CheckOut, @NumberOfAdults, @NumberOfChildren)", con);

Check your db is opened and if you made a mistake typing those strings in the constructors, if you see the exception details you can see the line where the exception is thrown and you will know if it's the con or cmd problem.

You get this exception when you try to call a method of a null object.

Edit: I see you said the error is thrown from this line:

cmd.Parameters.Add("@TypeOfRoom", comboBox1.SelectedItem.ToString());

This means the comboBox is giving the exception, probably because you haven't selected an item when you clicked on the button, since nothing is selected, the call to .ToString() is throwing null exception. Surround that part with a try catch like this:

try
{
    cmd.Parameters.Add("@TypeOfRoom", comboBox1.SelectedItem.ToString());
}catch(Exception e)
{
    //This code will be executed when the exception is thrown (when you 
    //haven't selected an item, so the selected item is null)
}

If you select an item and click the button and it still crashes, then the comboBox is null and you have to fix your code to make sure it is not null.

janavarro
  • 861
  • 2
  • 20
  • My connecting string is GREGJAMES\SQLEXPRESS when copied and pasted from properties, but when i paste it on the code there is a "Unrecognized escape sequence" I have to admit that to avoid the error i did put a extra "\" but i feel like thats where my main problem is now – James Craig May 07 '19 at 06:39
  • try this string: @"Data Source=GREGJAMES\SQLEXPRESS;Initial Catalog=Hotel;Integrated Security=True" When you put @ before a string, it ignores escape sequences. Make sure you also write it in one line, without linebreaks, because when you add @ it doesn't ignore linebreaks. – janavarro May 07 '19 at 06:42
  • Thank you for your help really, i got it solve but my next problem came up which is Conversion failed when converting the nvarchar value 'xxx ' to data type int. I'm just so new to this, im really sorry if im asking alot – James Craig May 07 '19 at 07:00
  • Check how to do the conversion in Google, sure someone has done it already. No offense, I've been there but maybe you need a stronger programming base to do the things you're doing. The questions you ask are too trivial. You need to know how to debug, how to convert types and many things you probably don't know yet. – janavarro May 07 '19 at 07:55
  • Yea, i'm really new to this stuff and trying to learn. Thanks for the help! – James Craig May 07 '19 at 08:53