Click here to Skip to main content
15,881,709 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
i have one textbox,DropDownList,checkboxlist.

Silver Gold, Gold,Sterling Silver,Silver Brass


4 String insert in Single Column but comma separated values.. like(Silver Gold,Silver Brass) or(Gold,Sterling Silver,Silver Brass)

then Access the Checkboxlist related the value can checkbox can checked....???

Problem:- data save in database but not properly save.. i mean comma saparated values....

My Code Is:-

protected void btnADDSAVE_Click(object sender, EventArgs e)
{
InsertMetal();
}

protected void InsertMetal()
{
SqlConnection con = new SqlConnection(str);

SqlCommand cmd = new SqlCommand();
cmd.CommandText = "sp_addnewproduct";
cmd.CommandType = CommandType.StoredProcedure;



cmd.Parameters.Add("@name", SqlDbType.VarChar).Value = txtName.Text.Trim();
cmd.Parameters.AddWithValue("@category", DropDownList1.SelectedItem.Value);

//SqlParameter metal = new SqlParameter("@metal", SqlDbType.VarChar); ;
// metal.Value = CheckBoxList1.SelectedValue;
// cmd.Parameters.Add(metal);


cmd.Parameters.AddWithValue("@metal", CheckBoxList1.SelectedItem.Text.Trim());
cmd.Connection = con;

string baby = "";
for (int i = 0; i < CheckBoxList1.Items.Count; i++)
{

if (CheckBoxList1.Items[i].Selected)
{
baby += CheckBoxList1.Items[i].Value + ",";

}
}
baby = baby.TrimEnd(',');

Response.Write(baby);

try
{

con.Open();
cmd.ExecuteNonQuery();

Response.Write("Added");
}
catch (Exception e)
//catch
{
throw e;
//Response.Write("NOT Added");
// return baby;
}
finally
{
con.Close();
con.Dispose();
}

}
Posted

1 solution

"Problem:- data save in database but not properly save.. i mean comma saparated values...."
That's where you are wrong!
Saving comma separated values in a database is a bad idea - it makes it very hard to work with when it comes to any significant changes. Think about trying to remove the "Silver" entry from this list:
"Silver Gold, Gold,Sterling Silver,Silver Brass"

in SQL, that's a PITA!

So if your DB has these stored in separate tables with foreign key links, than that's the right way! You don't show your table design, but converting a list of entries to a CSV in SQL is pretty easy:
SQL
SELECT SUBSTRING(
(SELECT ',' + MyValue FROM myTable
FOR XML PATH('')),2,100000) AS CSV
 
Share this answer
 
Comments
Richard Deeming 7-Aug-15 8:35am    
Be careful with the FOR XML PATH('') solution if your data contains "special" characters. You'll end up with XML encoded entities instead.

There's a workaround using FOR XML PATH(''), TYPE, along with several alternative approaches, documented on the SimpleTalk blog:
Concatenating Row Values in Transact-SQL[^]

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