user1147188
user1147188

Reputation: 135

Multiple select from checkboxes using c#

Hy..I have a checkbox with 5 choices. I want to insert the checked values into one table separated by a ' , '.Here is my code:

        string str = string.Empty;

        foreach (ListItem item in this.checkbox1.Items)
       {
            if (item.Selected)
           {
                str = str + ",";
           }
        }

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["chestionar"].ConnectionString);
        SqlCommand cmd = new SqlCommand("INSERT INTO Raspunsuri Values('" + str + "',@cnp,@data,'10')", con);

        cmd.Parameters.AddWithValue("@cnp", Session["sesiune_cnp"]);
        cmd.Parameters.AddWithValue("@data", DateTime.Now.ToLocalTime());


        try
        {
            con.Open();
            cmd.ExecuteNonQuery();
            Response.Redirect("User11.aspx");
        }

        catch (Exception ex)
        {
            Console.WriteLine("Error:" + ex);
        }
        finally
        {
            con.Close();
        }

My problem is that when I hit the insert button it doesn't insert the values that the user checked.I must assign to string str a value.What is that value??

Upvotes: 0

Views: 5201

Answers (4)

Ashraf Uddin
Ashraf Uddin

Reputation: 82

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MultipleCheckBoxesApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        string _concateString = "";
        private void checkBoxButton_Click(object sender, EventArgs e)
        {
            List<string> ourList = new List<string>();
            if (csharpCheckBox.Checked)
            {
                ourList.Add(csharpCheckBox.Text);
            }
            if (javaCheckBox.Checked)
            {
                ourList.Add(javaCheckBox.Text);
            }
            if (cCheckBox.Checked)
            {
                ourList.Add(cCheckBox.Text);
            }
            if (phpCheckBox.Checked)
            {
                ourList.Add(phpCheckBox.Text);
            }
            if (cplusCheckBox.Checked)
            {
                ourList.Add(cplusCheckBox.Text);
            }
            foreach (string checkList in ourList)
            {
                _concateString += checkList + " ,";
            }
            if (_concateString == string.Empty)
            {
                MessageBox.Show("Nothing Checked", "Error",
                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                MessageBox.Show(_concateString + " has been checked");
            }

            ourList.Clear();
            _concateString = string.Empty;



        }
    }
}

Upvotes: 0

TBohnen.jnr
TBohnen.jnr

Reputation: 5119

Change:

StringBuilder values = new StringBuilder();

if (item.Selected)  
{    
    if (sb.Length) > 0
        values.Append(","); // To ensure that the last char is not a comma after the loop
    values.Append(item.value);

}  


SqlCommand cmd = new SqlCommand("INSERT INTO Raspunsuri Values(@str,@cnp,@data,'10')", con);

Add:

cmd.Parameters.AddWithValue("@str", values.ToString()); 
  1. So we remove the sql injection you could possible get by passing the values as a parameter. Also, to get the selected value of a ListItem you use the Value property.

  2. Now all you do is add the value to a stringbuilder (you don't need to use a stringbuilder but it's more efficient if there are a lot of values in the listbox).

  3. Set the parameter's value from the StringBuilder

Upvotes: 0

ChrisF
ChrisF

Reputation: 137148

string str = string.Empty;

foreach (ListItem item in this.checkbox1.Items)
{
    if (item.Selected)
    {
        str = str + ",";
    }
}

The problem is that str never has a value so you are just writing a series of commas to the database - one for each item that's checked.

You need to append something else to the string to identify which options are selected - probably item.Value. So your code will become:

if (item.Selected)
{
    str += item.Value + ",";
}

However, using string concatenation like this isn't very efficient as it needs to recreate the string object every time (strings are immutable). So using StringBuilder will result in more efficient code.

Also is it OK that the the string ends with a comma? If not it's easy to remove:

str = str.TrimEnd(new char[] { ',' })

Upvotes: 3

Tigran
Tigran

Reputation: 62246

  • First: avoid concatenation of string in the loop. Strings in C# are immutable so you allocate a new memory on every iteration. Use StringBuilder() and its Append() method for that.

  • Never, ever write directly string into the SQL. ALways use a parameters. So your code has to be looked like this:

    SqlCommand cmd = new SqlCommand("INSERT INTO Raspunsuri   Values (@stringvalue,@cnp,@data, @tenvalue)", con);
    
    cmd.Parameters.AddWithValue("@stringvalue", str);
    cmd.Parameters.AddWithValue("@cnp", Session["sesiune_cnp"]);
    cmd.Parameters.AddWithValue("@data", DateTime.Now.ToLocalTime());
    

I think, by resolving this you will resolve your problem too.

Good luck.

Upvotes: 0

Related Questions