How to insert checkboxes checked into the access database?

advertisements
OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\jay.desai\Documents\Visual Studio 2008\Projects\Test\Test\Test.mdb");

con.Open();
OleDbCommand cmd = new OleDbCommand("insert into EmpTest values(@Emp_No,@Gender,@Language)", con);

            cmd.Parameters.AddWithValue("@Emp_No", textBox1.Text);
            if (radioButton1.Checked)
            {
                cmd.Parameters.AddWithValue("@Gender", radioButton1.Text);
            }
            else
            {
                cmd.Parameters.AddWithValue("@Gender", radioButton2.Text);
            }
            if (checkBox1.Checked)
            {
                cmd.Parameters.AddWithValue("@Language", checkBox1.Text);
            }
            if (checkBox2.Checked)
            {
                cmd.Parameters.AddWithValue("@Language", checkBox2.Text);
            }
            if (checkBox3.Checked)
            {
                cmd.Parameters.AddWithValue("@Language", checkBox3.Text);
            }
            if (checkBox4.Checked)
            {
                cmd.Parameters.AddWithValue("@Language", checkBox4.Text);
            }
            cmd.ExecuteNonQuery();
            con.Close();

when i click on submit button only the first checked checkbox value inserted in database??


If you need to write all the languages checked to the database you need to build a string with the cumulative text of the checkbox selected.

using(OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\jay.desai\Documents\Visual Studio 2008\Projects\Test\Test\Test.mdb"))
using(OleDbCommand cmd = new OleDbCommand("insert into EmpTest values(@Emp_No,@Gender,@Language)", con))
{
    con.Open();
    cmd.Parameters.AddWithValue("@Emp_No", textBox1.Text);
    cmd.Parameters.AddWithValue("@Gender", GetGender());
    cmd.Parameters.AddWithValue("@Language", GetLanguages());
    cmd.ExecuteNonQuery();
}

private string GetLanguage()
{
     StringBuilder result = new StringBuilder();
     if (checkBox1.Checked)
         result.AppendFormat("{0},", checkBox1.Text);
     if (checkBox2.Checked)
         result.AppendFormat("{0},", checkBox2.Text);
     if (checkBox3.Checked)
         result.AppendFormat("{0},", checkBox3.Text);
     if (checkBox4.Checked)
         result.AppendFormat("{0},", checkBox4.Text);
     if(result.Length > 0) result.Lenght--;
     return result.ToString();
}

private string GetGender()
{
    return (radioButton1.Checked ? radioButton1.Text : radioButton2.Text);
}

instead, if you need just one Language then you should remove your checkbox controls and use a radiobutton exclusive set of controls like you do for the Gender field