Click here to Skip to main content
15,889,877 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi
i am designing a registration page.i am having multiple checkboxes as hobbies.i want to insert all checkbox checked values into one coloum seperated by delimiter(,).
please anyone replyme.
i tried this.
C#
string s;
                  if (chkcricket.IsChecked==true)
                  {
                      s = "cricket";
                  }
                  if (chkhockey.IsChecked == true)
                  {
                      s = "hockey";
                  } if (chkbasketball.IsChecked == true)
                  {
                      s = "basketball";
                  } if (chkother.IsChecked == true)
                  {
                       s = "other";
                  }
                  SqlCommand cmd = new SqlCommand("insert into record(name,id,hobbies) values('"+txtname.Text+"','"+txtid.Text+"','"+s+"')",con);
Posted
Updated 29-Oct-13 23:21pm
v2
Comments
Pheonyx 30-Oct-13 5:05am    
Well what have you tried?
laxmi smiley 30-Oct-13 5:07am    
i tried by if statement.
Pheonyx 30-Oct-13 5:09am    
And what does that mean? Use the "improve question" and explain what you have tried, use consise/small code snippets to help show what you have done.
Also, explain what outcome it has given and what outcome you are trying to achieve.

1 solution

Try the following:
C#
StringBuilder hobbies = new StringBuilder();
if (chkcricket.IsChecked==true)
{
     hobbies.Append("cricket,");
}
if (chkhockey.IsChecked == true)
{
     hobbies.Append("hockey,");
}
if (chkbasketball.IsChecked == true)
{
      hobbies.Append("basketball,");
}
if (chkother.IsChecked == true)
{
        hobbies.Append("other");
}

SqlCommand cmd = new SqlCommand("insert into record(name,id,hobbies) values(@name,@id,@hobbies)",con);
cmd.Parameters.AddWithValue("@name", txtname.Text);
cmd.Parameters.AddWithValue("@id", txtId.Text);
cmd.Parameters.AddWithValue("@hobbies", hobbies.ToString());


I have used a stringbuilder to build the hobbies string (it is not the cleanest way to do it as over time you will have to keep extending that if statements collection.
I have also introduced Parameters into the SQL query to help prevent SQL Injection attacks.
 
Share this answer
 
Comments
laxmi smiley 30-Oct-13 6:03am    
nice solution
i want to seperate each hobbie with delimiter(,) for future use to display in grid.can you please guide me.
Pheonyx 30-Oct-13 6:12am    
The solution provided should separate them by commas as you required. If you look at all the strings apart from "Other" you will see they end with a comma.
laxmi smiley 30-Oct-13 6:15am    
ya thank u.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900