2014年7月13日 星期日

[RESOLVED] writing checkboxlist values to a table


Hi All,


I have a checkboxlist to let users select values. I need to grab the selected values and write to a database.


What would be the best and most efficient way to do this? Thanks for your help in advance.


            RepeatDirection="Horizontal">









foreach (ListItem li in checkboxList1.Items)
{
// If the list item is selected
if (li.Selected)
{
// Retrieve the value of the selected list item
Response.Write("Value = " + li.Value + ", ");
}
}



You can use LINQ also.



Hi,


If you want to insert the values into same column as mutiple rows you can try with the below code


protected void Button1_Click(object sender, EventArgs e)
{
//String variable to hold the selected items values
String str = "";
//Looping through items in checkboxlist
for (int i = 0; i <= checkboxList1.Items.Count - 1; i++)
{
//Checking whether items are selected or not
if (checkboxList1.Items[i].Selected)
{
//Adding the first item value
if (str == "")
{
str = checkboxList1.Items[i].Text;
}
// Adding
else
{
str += "," + checkboxList1.Items[i].Text;

}
}
}
//Creating connection object
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());
//Opening the connection
con.Open();
//Creating command object and passing values to query
//Change the query as per your need
SqlCommand cmd = new SqlCommand("Insert into YourTableName(YourColumnName) values('" + str + "')", con);
//Executing the query
cmd.ExecuteNonQuery();
}



Refer the below link for more details




If you want to insert the values into multiple column then you can use the below code


string updateQry = "UPDATE myTable SET col1 = @param1, col2 = @param2, col3 = @param3 WHERE ...";

using(SqlConnection con = new SqlConnection("connection string here"))
{
using(SqlCommand cmd = new SqlCommand(updateQry, con))
{
cmd.CommandType = CommandType.Text;
con.Open();

for (int i = 0; i < checkboxlist1.Items.Count; i++)
{
cmd.Paramters.AddWithValue("@param" + i.ToString(), checkboxlist1.Items[i].Selected);
}

cmd.ExecuteNonQuery();
}
}






沒有留言:

張貼留言