<asp:ListBox ID="MenuAccess" SelectionMode="Multiple" runat="server" />
if (MenuAccess.Items.Count > 0)
{
for (int i = 0; i < MenuAccess.Items.Count; i++)
{
if (MenuAccess.Items[i].Selected)
{
SqlConnection conn;
SqlCommand comm;
string connectionString1 = ConfigurationManager.ConnectionStrings["DataString"].ConnectionString;
conn = new SqlConnection(connectionString1);
comm = new SqlCommand("INSERT INTO Menus (LinkID) VALUES (@LinkID)", conn);
comm.Parameters.Add("@LinkID", System.Data.SqlDbType.Int);
comm.Parameters["@LinkID"].Value = MenuAccess.Items[i].Text;
}
try
{
conn.Open();
comm.ExecuteNonQuery();
}
finally
{
conn.Close();
}
}
}
if(!Page.IsPostBack)
{ //Bind listbox
}
Or share your code-behind on how you are binding the data to listbox.
if (Page.IsPostBack == true)
{
string IsCurrent = Request.Form["PAns"];
if (IsCurrent == "Y")
{
PAns.Visible = true;
PYes.Visible = true;
PNo.Visible = false;
BindMenuAccessList();
}
else
{
PAns.Visible = true;
PYes.Visible = false;
PNo.Visible = true;
BindMenuAccessList2();
}
}
protected void UserAdd_Click(object sender, EventArgs e)
{
if (MenuAccess.Items.Count > 0)
{
for (int i = 0; i < MenuAccess.Items.Count; i++)
{
if (MenuAccess.Items[i].Selected)
{
SqlConnection conn1;
SqlCommand comm1;
string connectionString = ConfigurationManager.ConnectionStrings["DataString"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("INSERT INTO ACC_Menus (LinkID) VALUES (@LinkID)", conn);
comm.Parameters.Add("@LinkID", System.Data.SqlDbType.Int);
comm.Parameters["@LinkID"].Value = MenuAccess.Items[i].Text;
try
{
conn.Open();
comm.ExecuteNonQuery();
}
finally
{
conn.Close();
}
}
}
}
}
comm.Parameters["@LinkID"].Value = MenuAccess.Items[i].Text;
comm.Parameters["@LinkID"].Value = Convert.ToInt32(MenuAccess.Items[i].Text);
foreach (ListItem li in ListBox1.Items)
{
if (li.Selected == true)
{
msg += "<BR>" + li.Text + " is selected.";
}
}
2: move try/finally inside if
3: Add catch block
4: If you have access to SqlProfiler then try to setup a trace and see if the command is executed and the value passed.