【问题标题】:How to get dynamically created checkboxes' value如何获取动态创建的复选框的值
【发布时间】:2015-03-04 19:25:46
【问题描述】:

我的 Webforms ASP.NET 4.5 应用程序中有一个用户表,该表由用户动态填充。在该表中,每个用户名之前都有复选框。我想删除我单击删除按钮后检查的所有用户。但是,当我单击删除按钮时,虽然调用了按钮单击事件,但不会调用选中复选框的 checkedchanged 事件。单击删除按钮时如何获取这些选中复选框的值?

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication3.Account
{
    public partial class Register : System.Web.UI.Page
    {
        private UserStore<IdentityUser> userStore;
        private UserManager<IdentityUser> userManager;
        private List<string> users = new List<string>();
        protected void Page_Load(object sender, EventArgs e)
        {
            userStore = new UserStore<IdentityUser>();
            userManager = new UserManager<IdentityUser>(userStore);
            if (!IsPostBack)
            {
                fillTable();
            } 
        }

        private void fillTable()
        {
            TableHeaderRow headerRow = new TableHeaderRow();
            TableHeaderCell hCell1 = new TableHeaderCell();
            hCell1.CssClass = "col-md-1";
            hCell1.Text = "#";
            TableHeaderCell hCell2 = new TableHeaderCell();
            hCell2.Text = "Kullanıcı Adı";
            hCell2.CssClass = "col-md-5";
            headerRow.Controls.Add(hCell1);
            headerRow.Controls.Add(hCell2);
            headerRow.Controls.Add(new TableHeaderCell() { CssClass = "col-md-3" });
            headerRow.Controls.Add(new TableHeaderCell() { CssClass = "col-md-3" });
            headerRow.TableSection = TableRowSection.TableHeader;
            tblUser.Rows.Add(headerRow);

            foreach (IdentityUser user in userManager.Users.ToList())
            {
                TableRow row = new TableRow();
                TableCell cell1 = new TableCell();
                CheckBox checkBox = new CheckBox();
                checkBox.InputAttributes.Add("value", user.Id);
                checkBox.CheckedChanged += checkBox_CheckedChanged;
                cell1.Controls.Add(checkBox);
                cell1.HorizontalAlign = HorizontalAlign.Center;
                TableCell cell2 = new TableCell();
                cell2.Text = user.UserName;
                TableCell cell3 = new TableCell();
                HyperLink link = new HyperLink();
                link.Text = "Şifreyi Değiştir";
                cell3.Controls.Add(link);
                row.Controls.Add(cell1);
                row.Controls.Add(cell2);
                row.Controls.Add(new TableCell());
                row.Controls.Add(cell3);
                tblUser.Rows.Add(row);
                row.TableSection = TableRowSection.TableBody;
            }
        }

        void checkBox_CheckedChanged(object sender, EventArgs e)
        {
            if (ViewState["userList"] != null)
            {
                users = (List<string>)ViewState["userList"];
            }
            CheckBox checkbox = (CheckBox)sender;
            if (checkbox.Checked)
            {
                if (!users.Contains(checkbox.InputAttributes["value"]))
                {
                    users.Add(checkbox.InputAttributes["value"]);
                }
            }
            else
            {
                if (users.Contains(checkbox.InputAttributes["value"]))
                {
                    users.Remove(checkbox.InputAttributes["value"]);
                }
            }

            ViewState["userList"] = users;
        }

        protected void btnDeleteUser_Click(object sender, EventArgs e)
        {
            foreach (string id in users)
            {
                IdentityUser user = userManager.FindById(id);
                userManager.Delete(user);
            }
            fillTable();
        }

    }
}

【问题讨论】:

  • 有反馈吗?

标签: c# asp.net checkbox webforms


【解决方案1】:

试试这个:

foreach(TableRow row in tblUser) 
{
    foreach(TableCell cell in row) 
    {
        foreach(Control ctrl in cell) 
        {
            if (ctrl.GetType() == CheckBox) 
            {
                /* get value here */
            }
        }
    }
}

【讨论】:

    【解决方案2】:

    从创建动态复选框列表的 foreach 循环中删除以下行:

    checkBox.CheckedChanged += checkBox_CheckedChanged;
    

    请添加下面的行而不是上面的行:

    checkBox.Attributes.Add("name", "chkDel");
    checkBox.Attributes.Add("onclick", "UncheckDelAll('chkDelAll','chkDel')");
    

    在页面顶部的 javascript 下方:

    function UncheckDelAll(HeaderChk, RowChk) {
    
            var cnt = 0; //Count of all the check boxes
            objSelected = document.getElementsByName(HeaderChk)
            obj = document.getElementsByName(RowChk)
            if (obj != null) {
                cnt = obj.length;
                for (var i = 0; i < cnt; i++) {
                    if (obj[i].checked == true);
                    cnt = 1;
    
                }
                if (cnt == 1)
                    objSelected[0].checked = false;
    
            }
        }
    

    这里是删除按钮点击事件逻辑:

    protected void lkDelete_Click(object sender, EventArgs e)
    {
    string sPrimaryIds = (string)Request.Params["chkDel"];
    // Write your delete query functionality over here
    // Your delete query like this
    // delete from [tablename] where UserId in (sPrimaryIds)
    }
    

    【讨论】:

      【解决方案3】:

      在你的 ByttonClickEvent 中

      protected void btnDeleteUser_Click(object sender, EventArgs e)
      {
      foreach(var row in tblUser.Rows)
       {
         var tempcheckBox= row.Controls[0] as CheckBox;
         if(tempcheckBox.IsChecked)
          {
             //your code
          }
       }
      }
      

      row.Controls[0] 因为复选框被插入到第一列中 移动Page_LoadComplete方法中的dataBinding进程和 删除测试if(!IsPostBack)

      事实上,如果您调用 postBack,您首先会通过 Pre_Init、PageLoad、Your EventHandler,然后是 Page_Load Complete。

      因此,如果您的绑定过程是在 Page_Load 中完成的。你会自动在你的 eventHandler 中找到你的 gridView,因为它是在 PageLoad 中初始化的。

      【讨论】:

      • tblUser 返回 0 行
      • 它是 0 因为页面中的这个代码 Load if (!IsPostBack) { fillTable(); }
      • 在每个 Check_event 中,您都进行了回发并且您没有更新 tblUser 数据源,这就是 count = 0 的原因
      • 我删除了 if(!IsPostBack) 但它只在第一次之后才有效,然后 checkbox.Checked 返回 false 虽然它被选中
      猜你喜欢
      • 1970-01-01
      • 2019-06-16
      • 2017-10-02
      • 2017-05-07
      • 2015-01-16
      • 2023-03-04
      • 2019-12-20
      • 2015-07-22
      • 2014-08-06
      相关资源
      最近更新 更多