【问题标题】:Getting the column reference of a Gridview Cell by string instead of index通过字符串而不是索引获取 Gridview Cell 的列引用
【发布时间】:2011-04-14 21:08:36
【问题描述】:

我正在向 gridview 动态添加一列...它是一列复选框 - 用户检查它们以确定他们要打印的行。我希望能够在不使用数字索引的情况下获得对单元格的引用:

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.Cells[4].Controls.Count == 0)
            {
                CheckBox cbPrint = new CheckBox();
                cbPrint.ID = "chkPrint";
                cbPrint.Checked = false;
                e.Row.Cells[4].Controls.Add(cbPrint); <--- this line
            }
        }

我希望能够像在 e.Row.Cells["Print"] 中使用“打印”,就像在 DataSet 中使用列一样 - 例如:ds.Tables[0].Rows[3][" Print"],其中 print 指定列。我希望能够做到这一点,因为打印列在每个 GridView 中可能不在同一个位置,并且使用数字索引可能不会一直有效。有没有办法使用字符串列引用来获取单元格??

【问题讨论】:

    标签: gridview


    【解决方案1】:

    这是我想出来的……我写了一个小函数来根据标题文本获取列的索引。

            GridView gv = (GridView)sender //inside OnRowDataBound
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (e.Row.Cells[GetIndex(gv, "Print")].Controls.Count == 0)
                {
                    CheckBox cbPrint = new CheckBox();
                    cbPrint.ID = "chkPrint";
                    cbPrint.Checked = false;
                    e.Row.Cells[GetIndex(gv, "Print")].Controls.Add(cbPrint);
                }
            }
    

    GetIndex 方法:

           public static int GetIndex(GridView gv, string columnText)
           {
               for (int i = 0; i < gv.Columns.Count; i++)
                   if (gv.Columns[i].HeaderText == columnText)
                       return i;
               return -1;
           }
    

    如果带有该标题文本的列存在,那么它将返回索引。如果不是,那么它将返回 -1 并且您会收到一个错误...因此,如果您不知道该列是否存在,则需要在此处进行一些错误处理。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-17
      • 1970-01-01
      • 2011-01-25
      • 1970-01-01
      • 2016-11-15
      • 1970-01-01
      • 2021-07-01
      • 1970-01-01
      相关资源
      最近更新 更多