dimanche 15 novembre 2015

Update db based on checkbox selection(s) in Repeater control

In Visual Studio, I have a Repeater. This functions fine. It has checkboxes and labels. If someone checks the checkboxes in the Repeater, I want my button to be clicked and update my database based on what is and isn't checked.

My code currently selects ALL fields and updates ALL of them in the database (all rows get set to visible = 0). I want ONLY the CHECKED boxes to get Visible = 0. I need a WHERE statement that somehow sees only the checked fields, but I am at a loss of how to do this.

Here is my Repeater:

        <asp:Repeater ID="Repeater1" runat="server">
   <ItemTemplate>
     <table>
        <tr>
            <td>
 <asp:CheckBoxList ID="CheckBoxList1" runat="server">
       <asp:ListItem></asp:ListItem></asp:CheckBoxList>
            </td>
              <td> <asp:Label ID="lblTest" runat="server" Text='<%# Eval("MyColumn") %>'></asp:Label>
            </td>
     </table>
   </ItemTemplate>
</asp:Repeater>

Here is my button:

protected void ButtonSubmit_Click(object sender, EventArgs e)
    {

        using (SqlConnection sqlConn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["Events2"].ConnectionString))
        {
            sqlConn2.Open();

            using (SqlCommand sqlCmd2 = new SqlCommand())
            {
                sqlCmd2.Connection = sqlConn2;
                sqlCmd2.CommandType = System.Data.CommandType.Text;

                foreach (RepeaterItem aItem in Repeater1.Items)
                {
                    CheckBoxList CheckBoxList1 = (CheckBoxList)aItem.FindControl("CheckBoxList1");
                    foreach (ListItem listItem in CheckBoxList1.Items)
                    {
                        if (listItem.Selected == true)
                        {
                        sqlCmd2.CommandText = string.Format("UPDATE FormField SET Visible = 0");
                        sqlCmd2.ExecuteNonQuery();
                        }
                        else
                        {
                            //do something else
                        }
                    }


                } sqlConn2.Close();

            }

        }
    }




Aucun commentaire:

Enregistrer un commentaire