简体   繁体   English

没有为动态创建的复选框调用事件处理程序

[英]Event Handler is not getting called for dynamically created checkboxes

I am kind of new to C# and Asp.Net, so this question might sound repetitive but I am not able to find a solution for this particular problem. 我是C#和Asp.Net的新手,所以这个问题听起来很重复,但是我无法找到解决此特定问题的解决方案。

I have two buttons on my HTML page and a single class in .cs file. 我的HTML页面上有两个按钮,而.cs文件中有一个类。 On one of the button clicks, I create a table programmatically (dynamically). 在单击按钮之一时,我以编程方式(动态)创建了一个表。 The table contains some checkboxes which are also created dynamically. 该表包含一些复选框,这些复选框也是动态创建的。 Table creation is one of the last tasks that I perform. 创建表是我执行的最后一项任务。 Before that, I read several files and extract data from them to create the table. 在此之前,我读取了几个文件并从中提取数据来创建表。 After the table is drawn, the user can select one or more checkboxes. 绘制表格后,用户可以选择一个或多个复选框。

Now, how on second button click, can I know that which of the checkboxes were checked before the page reload? 现在,如何单击第二个按钮,我是否可以知道在重新加载页面之前选中了哪个复选框? Currently I have made all these checkboxes member variables of the the only class that I have in the .cs file. 目前,我已经将所有这些复选框成员变量.cs文件中唯一的类。

I tried adding checkbox event handler through C# code. 我尝试通过C#代码添加复选框事件处理程序。 But the handler is not getting called when the checkbox is checked. 但是选中此复选框时,不会调用处理程序。 I don't want to set the 'autopostback' property of the checkbox to true since if thats set true, the page reloads after checking one of the checkboxes. 我不想将复选框的'autopostback'属性设置为true,因为如果那设置为true,则在选中其中一个复选框后将重新加载页面。 User should be able to select multiple checkboxes. 用户应该能够选择多个复选框。

Add your checkboxes dynamically and set a unique name for each checkbox. 动态添加您的复选框,并为每个复选框设置唯一的名称。 Checkboxes are only posted back to the server if the checkbox is checked, so you can test to see if it is checked by checking Request.Form to see if the name exists. 如果复选框被选中,复选框仅被发布回服务器,因此您可以通过检查Request.Form以查看名称是否存在来测试是否被选中。 For example, lets say you named your check boxes chk_[0-9] (ie chk_0, chk_1 etc till 9), you could check if they ticked by doing: 例如,假设您将复选框chk_ [0-9]命名为chk_ [0-9](即chk_0,chk_1等,直到9),则可以通过执行以下操作来检查它们是否被选中:

for(int i=0; i < 10; i++)
{
    string chk_name = "chk_" + i.ToString();
    if (Request.Form[chk_name] != null)
    {
        //checkbox is checked
    }
    else
    {
        //checkbox is not checked
    }
}

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

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