...

View Full Version : insert multiple rows from checkboxlist into sql table



liran.e
02-04-2012, 05:23 PM
Hi,

I have a web form with a checkbox list

I've added a button and I'd like to insert whatever rows the user checked into an exisiting sql table

I'm a newbie to asp , and I'd love some help

btw - I'm using Visual Studio 2010 & SQL 2008 r2

alykins
02-04-2012, 06:39 PM
something like this should work- note: i did not build/compile it or test it as can be seen by bogus names for connecction string and SQL text- Also worth noting is that is a bad way to do connection strings and you should also never do inline SQL- I would call a stored proc for the command and call the web.config file for the connection string- I did it this way so you could see what I was doing


protected void btn_Click(object sender, EventArgs e)
{
foreach (CheckBox cb in Panel1.Controls)
{
if (cb.Checked)
CheckBoxToSQL(cb.Text);
}
}

private void CheckBoxToSQL(string CheckBoxName)
{
string connString = "my SQL connection string";
string query = string.Format("insert into dbo.MyTable ([CheckBoxName]) values ('{0}')", CheckBoxName);
SqlConnection conn = new SqlConnection(connString);
using (conn)
{
SqlCommand cmd = new SqlCommand(query, conn);
using (cmd)
{
cmd.CommandType = CommandType.Text;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
}

alykins
02-04-2012, 06:43 PM
Also worth noting is you may have to do that button call function like this...


protected void btn_Click(object sender, EventArgs e)
{
foreach (object obj in Panel1.Controls)
{
CheckBox cb = obj as CheckBox;
if (cb.Checked)
CheckBoxToSQL(cb.Text);
}
}


if you do it this way you will probably need to do some more code to handle "what happens" if the object is not a CheckBox



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum