选中gridview中以编程方式创建的列内的复选框

时间:2014-10-01 09:14:29

标签: asp.net vb.net gridview checkbox

我使用rowdatabound事件在gridview中创建了一个复选框列:

    If e.Row.RowType = DataControlRowType.DataRow Then

               'RETRIEVE THE NUMBER OF REQUIRED COLUMNS FROM THE DATABASE:
                Dim newlist As New List(Of ID_CLASS)
                newlist = SELECT_ID(datenow)


                Dim i As Integer = 1
                For Each value In newlist
                    Dim check1 As New CheckBox()

                    'Adds a new checkbox column for each value.ID:
                    check1.ID = value.ID
                    check1.Checked = False
                    e.Row.Cells(i).Controls.Add(check1)
                    i = i + 1
                Next
     End If

现在,在另一个函数中(在同一模块中),我需要检查一些特定的复选框。这是我现在使用的代码(但不起作用):

         Dim i As Integer = 0
         Dim newlist As New List(Of ID_CLASS)
         newlist = SELECT_ID(datenow)

           For each value in newlist
                While i < 24
                    row_a = GridView1.Rows(i)
                    Dim ID As String = value.ID

                   'IF A CONDITION IS MET:
                        Dim check1 As CheckBox = TryCast(row_a.FindControl(ID), CheckBox)
                        check1.Checked = True

                    i = i + 1
                End While
            Next

这是我得到的错误:'对象参考未设置为对象的实例' 我认为这是因为我添加的checkbox.ID没有在gridview中呈现。但我不知道如何以这样的方式添加ID,它将在模块中持续存在

请帮忙。感谢

1 个答案:

答案 0 :(得分:1)

您使用Dim i As Integer = 1的rowdatabound事件中的第一个假设。因此,假设索引0处没有文本框。而在第二种方法中的theb

  Dim i As Integer = 0 .

我在C#中做过类似的事情,它永远不会让我失望。以下是我通常的做法。首先让我们说你有一个三列网格。第一列是checbox列。您可以访问下面的复选框。

C#
int rowIndex = 0;

if(GridView1.Rows.Count > 0) //Check your grid for rows.
{
  for(int i=1; i < GridView1.Rows.Count; i++)
  { 
     CheckBox check = (CheckBox) GridView1.Rows[rowIndex].Cells[0].FindControl("checkbox1");
     //In the above, checkbox1 is your textbox name.
     //RowIndex is the row number/index.
     //Cells[0] assumin the first colum/cell of the gridview contain checboxes only. It can be 1,2 ..

     check.Checked = true;

     rowIndex ++;

  }

}

注意当你说&#34;创建一个复选框列&#34; 。然后我假设有一个复选框的列。列索引很重要。 0表示第一列,1表示第二列.....

in

VB
 Dim rowIndex As Integer = 0

if(GridView1.Rows.Count > 0) //Check your grid for rows.

   for each Datarow row in Gridview1.Rows
      while rowIndex < 24

      DIM check AS CheckBox= TryCast(GridView1.Rows[rowIndex].Cells[0].FindControl("checkbox1"), CheckBox);
     check.Check = true;
     rowIndex ++;
    END while

Next 

我不习惯VB只是尝试。但是之前已经在C#中编写了相似的功能,我确信它有效。希望它有所帮助。