Dynamically (programmatically) adding flags and check changes

I have a problem adding multiple checkboxes and an event handler programmatically. All checkboxes look normal, but when clicked they do nothing. Does anyone know what I'm doing wrong?

My code is:

foreach (Statement i in theseStatements)
{
    box = new CheckBox();
    box.Text = i.StatementText;
    box.AutoPostBack = true;
    box.CheckedChanged += new EventHandler(this.CheckedChange);
    PlaceHolder.Controls.Add(box);
}

protected void CheckedChange(object sender, EventArgs e) 
{
    CheckBox x = (CheckBox)sender;
    Instructions.Text = "change";            
    WorkPlaceHazardsBox.Text += x.Text;
} 
+3
source share
8 answers

You should do the following:

  • Set a property IDfor each instance CheckBoxthat you create in your loop foreach.
  • For PostBacks, make sure your CheckBoxes are created and the event handler is CheckedChangedconnected at some point in the page life cycle before the control events are activated.
+3

, :

  • ,
  • , ( )

- , .

+2

"" WorkPlaceHazards , , .

, ?

0

, " " - ?

, - , , , .. - ( , ) ASP.NET. , .

0

Request [ "controlname" ], . .

CheckBoxList

0

- VS2005 # (. ). . , - . , StatementText ?

...

<body>
    <form id="form1" runat="server">
    <div>
        <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
        Instructions: <asp:TextBox ID="Instructions" runat="server" />
        WorkPlaceHazardsBox: <asp:TextBox ID="WorkPlaceHazardsBox" runat="server" />
    </div>
    </form>

</body>

...

using System;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace CheckboxMadness
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            List<string> statements = new List<string>(new string[] { "foo", "bar" });

            foreach (string i in statements)
            {
                CheckBox box = new CheckBox();
                box.Text = i;
                box.AutoPostBack = true;
                box.CheckedChanged += new EventHandler(this.CheckedChange);
                PlaceHolder1.Controls.Add(box);
            }

        }
        protected void CheckedChange(object sender, EventArgs e)
        {
            CheckBox x = (CheckBox)sender;

            Instructions.Text = "change";

            WorkPlaceHazardsBox.Text += x.Text;
        }
    }
}
0

CheckedChanged , , . TableCell s. CheckBox CheckedChanged (, Table - , CheckBox ).

.

0
var box = new CheckBox();
-1

Source: https://habr.com/ru/post/1704450/


All Articles