0

I have a form with:

textbox  roomnumber    (table column number int)  
combobox roomtype      (table column type   varchar)  
textbox  phone         (table column phone  varchar)  
radiobuttons yes or no (table column free   varchar)  

I have a table with columns:

int number  
varchar type  
varchar phone  
varchar free  

I have to enter these values from windows form into table.

I wrote the following code. but do not understand how to get radiobutton values in the insert query.

string free = "";

if (rbyes.Checked)
{
    free = "yes";
}
else if (rbno.Checked)
{
    free = "No";
}

SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into rooms values(number='" + txtroomno.Text + "',type = '" + cbroomtype.SelectedValue.ToString() + "',phone='" + txtphone.Text + "',free)";
cmd.ExecuteNonQuery();
MessageBox.Show("record inserted succeessfully");

Thank you in advance

Dale K
  • 25,246
  • 15
  • 42
  • 71
LMS
  • 19
  • 4
  • 1
    If free is a `bit` you can simply store a boolean. I would strongly recommend that you parameterize your query also to prevent SQL injection. – Cameron Tinker Sep 29 '20 at 19:30

1 Answers1

1

The INSERT statement isn't quite right. You need to define the columns you want to set on the table when inserting. Then you can add your parameterized values with something like the following:

string free = "no";

if (rbyes.Checked)
{
    free = "yes";
}

SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = @"insert into rooms(number, type, phone, free)
                    values(@number, @type, @phone, @free)";
cmd.Parameters.AddWithValue("@number", txtroomno.Text);
cmd.Parameters.AddWithValue("@type", cbroomtype.SelectedValue.ToString());
cmd.Parameters.AddWithValue("@phone", txtphone.Text);
cmd.Parameters.AddWithValue("@free", free);

try {
  cmd.Open();
  cmd.ExecuteNonQuery();

  MessageBox.Show("Record inserted successfully");
}
catch (SqlException ex) {
  MessageBox.Show("An error has occurred: " + ex.Message, 
                   "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

If you have any control over the database table schema, I would recommend changing the free column to a bit type. This will ultimately save space in the long run. Then it would be just storing a boolean instead of a string/varchar.

Cameron Tinker
  • 9,634
  • 10
  • 46
  • 85