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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/626889/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 10:51:15  来源:igfitidea点击:

Dynamically (programatically) adding check boxes and checkedchanged events

c#asp.netevent-handling

提问by Comanighttrain

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

采纳答案by Ken Browning

You should do the following:

您应该执行以下操作:

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

回答by casperOne

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.

如果每个复选框有一个说明文本框和一个 WorkPlaceHazards 文本框,则必须有一种方法将单击的复选框与其他两个控件相关联。

If that's not the case, then what are they supposedto be doing?

如果不是这样,那么他们该做什么?

回答by Chris Holmes

var box = new CheckBox();

回答by Jon Skeet

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. I think you'll have to study the page life cycle and control identification side of things reasonably carefully.

如果您必须为复选框分配 ID,我不会感到惊讶 - 请记住,在回发时,您将获得一个新页面,因此必须重新创建所有复选框,然后确定选中了哪个复选框等等。这是进入 ASP.NET 的(对我而言,无论如何)有点黑魔法的一面。我认为您必须合理仔细地研究页面生命周期并控制事物的识别方面。

回答by eglasius

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
  • 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
  • 在初始加载和进一步回发中都添加了相同的复选框列表
  • 您为每个复选框设置不同的 ID
  • 验证您是否收到回发(在页面加载中设置断点)
  • 控件在页面加载时添加到页面,或者在页面初始化时更好

If you are trying to do something different than that, update us with more info.

如果您尝试做一些与此不同的事情,请向我们提供更多信息。

回答by eglasius

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 作为替代,而不是动态添加的复选框

回答by Aaron Daniels

I copied your code into a new VS2005 C# web project (see below). 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?

我将您的代码复制到一个新的 VS2005 C# web 项目中(见下文)。您的代码有效。在这个片段之外可能还有其他事情发生。或者,所有语句集合中的 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;
        }
    }
}

回答by xcx

CheckedChangedmay not work if embedded in another control, e.g. embedded in TableCells. Have a try to create a CheckBoxand add CheckedChangedbefore creating an outer control (e.g. Table is outer control if CheckBoxis embedded in Table's cells).

CheckedChanged如果嵌入在另一个控件中,例如嵌入在TableCells 中,则可能不起作用。在创建外部控件之前尝试创建CheckBox和添加CheckedChanged(例如,如果CheckBox嵌入在表格的单元格中,则表格是外部控件)。

It could fix the problem in some cases.

在某些情况下,它可以解决问题。