遍历 GridView 中的所有行

编程入门 行业动态 更新时间:2024-10-26 10:32:34
本文介绍了遍历 GridView 中的所有行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..
 <asp:TemplateField HeaderText="Select">
 <ItemTemplate>
 <asp:CheckBox ID="chkSelected" runat="server" Checked="false"></asp:CheckBox>
  </ItemTemplate>
 </asp:TemplateField>

下面的代码工作正常,但有一个错误:

elow code works fine but there is a bug :

如果 Employee 对象返回了 5 行,我试图根据 id 选中复选框,但它只匹配最后一个 id - 它假设检查了所有 5 行..

if Employee object has return 5 rows and i am trying to checked the check box based on the ids but instead its just matching only the last id - it suppose to checked all 5 rows..

List<Employee> result = new List<Employee>();
long Id = (long)Session["Id"];
result = Employee.GetEmployeeById(Id);

foreach (GridViewRow row in gv.Rows)
{
   CheckBox chkBox = row.FindControl("chkSelected") as CheckBox;
   if (c != null)
   {
      if (result.Count > 0)
      {
          foreach (Employee item in result)
          {
             Label Id = row.FindControl("lblId") as Label;
             if (Id.Text == item.Id.ToString())
             {
                 chkBox.Checked = true;
             }
             else
             {
                chkBox.Checked = false;
             }
           }
       }

推荐答案

看看你的逻辑——你只有一个复选框.您在员工循环中取消选中和选中相同的控件.每个网格行是否都有一个复选框,应根据 id 存在于员工列表中的条件进行选择?

Look at your logic - you only have the one checkbox. You're unchecking and checking the same control in the employee loop. Does each grid row have a checkbox that should be selected based on the condition the id exists in the employee list?

 foreach (GridViewRow row in gv.Rows)
    {
        Label Id = row.FindControl("lblId") as Label;
        var result = Employee.GetEmployeeById(Id.Text);
        if (result.Count > 0)
        {
            CheckBox chkBox = row.FindControl("chkSelected") as CheckBox;
            if (chkBox != null)
            {
                chkBox.Checked = result.Any(x => x.Id.ToString() == Id.Text);

            }
        }

    }

这篇关于遍历 GridView 中的所有行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-01 10:19:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/828300.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:遍历   GridView

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!