简体   繁体   English

动态(以编程方式)添加复选框和checkedchanged事件

[英]Dynamically (programatically) adding check boxes and checkedchanged events

I am having a bit of a problem adding a few check boxes and an event handler programatically.我在以编程方式添加一些复选框和事件处理程序时遇到了一些问题。 The check boxes all appear fine, but they don't do anything when clicked.复选框看起来都很好,但单击时它们不做任何事情。 Does anyone have any idea what I am doing wrong?有谁知道我做错了什么?

My code:我的代码:

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;
} 

You should do the following:您应该执行以下操作:

  1. Set the ID property for each instance of CheckBox you create in your foreach loop.为您在foreach循环中创建的每个CheckBox实例设置ID属性。
  2. For PostBacks, ensure that your CheckBoxes are created and CheckedChanged event handler is attached at some point of the page life-cycle before control events are raised对于 PostBacks,请确保在引发控制事件之前,在页面生命周期的某个时间点创建 CheckBoxes 并附加CheckedChanged事件处理程序

Make sure to verify you are doing the following:确保验证您正在执行以下操作:

  • The same list of checkbox is being added on both the initial load and further postbacks在初始加载和进一步回发中都添加了相同的复选框列表
  • You set a different ID to each checkbox您为每个复选框设置了不同的 ID
  • Verify you are getting a postback (set a break point in Page Load)验证您是否收到回发(在页面加载中设置断点)
  • The controls are added to the page on Page Load, or even better on Page Init控件在页面加载时添加到页面,甚至在页面初始化时更好

If you are trying to do something different than that, update us with more info.如果您尝试做一些不同的事情,请向我们提供更多信息。

When you say they "don't do anything" - are you getting the postback?当您说他们“什么都不做”时-您收到回发了吗?

I wouldn't be surprised if you had to assign IDs to the checkboxes - bear in mind that on the postback, you'll get a new page, so it'll have to recreate all the checkboxes, then work out which one was checked etc. This is getting into what is (to me, anyway) somewhat black magic side of ASP.NET.如果您必须为复选框分配 ID,我不会感到惊讶 - 请记住,在回发时,您将获得一个新页面,因此必须重新创建所有复选框,然后确定哪个复选框被选中等等。这正在进入(对我来说,无论如何)ASP.NET 有点黑魔法的一面。 I think you'll have to study the page life cycle and control identification side of things reasonably carefully.我认为您必须合理仔细地研究页面生命周期并控制事物的识别方面。

CheckedChanged may not work if embedded in another control, eg embedded in TableCell s.如果嵌入在另一个控件中,例如嵌入在TableCell中, CheckedChanged可能不起作用。 Have a try to create a CheckBox and add CheckedChanged before creating an outer control (eg Table is outer control if CheckBox is embedded in Table's cells).在创建外部控件之前尝试创建一个CheckBox并添加CheckedChanged (例如,如果CheckBox嵌入在 Table 的单元格中,则 Table 是外部控件)。

It could fix the problem in some cases.在某些情况下,它可以解决问题。

If you have one Instructions textbox and one WorkPlaceHazards textbox per checkbox, then you have to have a way to associate the checkbox that was clicked with those other two controls.如果每个复选框有一个 Instructions 文本框和一个 WorkPlaceHazards 文本框,那么您必须有一种方法将单击的复选框与其他两个控件相关联。

If that's not the case, then what are they supposed to be doing?如果不是这样,那么他们该做什么?

You can get value by Request["controlname"] method when you inserted control in runtime.You must set Unique ID for each control.在运行时插入控件时,可以通过Request["controlname"] 方法获取值。您必须为每个控件设置唯一ID。

However you can use CheckBoxList as an alternative instead of dynamically added checkboxes但是,您可以使用 CheckBoxList 代替动态添加的复选框

I copied your code into a new VS2005 C# web project (see below).我将您的代码复制到一个新的 VS2005 C# web 项目中(见下文)。 Your code works.您的代码有效。 There may be something else going on outside of this snippet.在这个片段之外可能还有其他事情发生。 Or, is the StatementText property in all of your statements collection always empty?或者,您的所有报表集合中的 StatementText 属性是否始终为空?

Page...页...

<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>

Code behind...后面的代码...

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;
        }
    }
}
var box = new CheckBox();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM