1

Ive added this code to get a column in my grid with checkboxes:

<Columns>
    <asp:TemplateField HeaderText="Visitor"  HeaderStyle-Width="20" FooterStyle-HorizontalAlign="Center">
        <ItemTemplate>
            <asp:CheckBox ID="myCheckBox" runat="server"/>
        </ItemTemplate>
        <FooterStyle HorizontalAlign="Center" />
        <HeaderStyle Width="20px" />
        <ItemStyle HorizontalAlign="Center" />
    </asp:TemplateField>

and i want to get the value of a checkbox but i get "Object reference not set to an instance of an object." error. Here is where i try to call it and i get the error:

Dim checkb As String
For Each row As GridViewRow In orderGrid.Rows
    Dim chk As CheckBox = CType(row.FindControl("myCheckBox"), CheckBox)
    **checkb  = Request.Form("myCheckBox")**
Next row

Any idea of how to get the correct value of the checkbox?

4
  • First define value then try to fetch value! Commented May 13, 2013 at 14:03
  • the value is suppose to be defined when i click the checkbox and then i click send. I just want to check these values because there is a bug among them Commented May 13, 2013 at 14:07
  • Show that code where you're defining checkbox value Commented May 13, 2013 at 14:09
  • i dont define the value. Defined i meant that when i click check then a value is suppose to be defined on the checkbox, but i dont do anything with the code to set a value. Thats what i want to check if there is an acual value. Because sometimes the checkbox is true and sometimes is false. Long story for that, so i just need to see if any content is assigned when true and when is false Commented May 13, 2013 at 14:21

4 Answers 4

2

Basically, you can loop though GridView1.Rows and get the Checkboxes.

Note: I wrote in C# and converted using converter so my VB code might be a bit weird.

enter image description here

<asp:GridView runat="server" ID="GridView1" 
    AutoGenerateColumns="False" DataKeyNames="Id">
    <Columns>
        <asp:TemplateField HeaderText="Visitor">
            <ItemTemplate>
                <asp:CheckBox ID="myCheckBox" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField HeaderText="FirstName" DataField="FirstName" />
        <asp:BoundField HeaderText="LastName" DataField="LastName" />
    </Columns>
</asp:GridView>
<asp:Button runat="server" ID="SubmitButton" 
    OnClick="SubmitButton_Click" Text="Submit" />

Public Class User
    Public Property Id() As Integer
        Get
            Return m_Id
        End Get
        Set
            m_Id = Value
        End Set
    End Property
    Private m_Id As Integer
    Public Property FirstName() As String
        Get
            Return m_FirstName
        End Get
        Set
            m_FirstName = Value
        End Set
    End Property
    Private m_FirstName As String
    Public Property LastName() As String
        Get
            Return m_LastName
        End Get
        Set
            m_LastName = Value
        End Set
    End Property
    Private m_LastName As String
End Class

Protected Sub Page_Load(sender As Object, e As EventArgs)
    If Not IsPostBack Then
        Dim collection = New List(Of User)() With { _
            New User() With { _
                .Id = 1, _
                .FirstName = "John", _
                .LastName = "Doe" _
            }, _
            New User() With { _
                .Id = 2, _
                .FirstName = "Marry", _
                .LastName = "Doe" _
            }, _
            New User() With { _
                .Id = 3, _
                .FirstName = "David", _
                .LastName = "Newton" _
            } _
        }

        GridView1.DataSource = collection
        GridView1.DataBind()
    End If
End Sub

Protected Sub SubmitButton_Click(sender As Object, e As EventArgs)
    For Each row As GridViewRow In GridView1.Rows
        Dim checkBox = TryCast(row.FindControl("myCheckBox"), CheckBox)
        If checkBox.Checked Then
            ' Get the ID of selected row
            Dim id = GridView1.DataKeys(row.DataItemIndex).Value
        End If
    Next
End Sub
Sign up to request clarification or add additional context in comments.

Comments

2

I'm going off memory here, but I think if you defined the "Value" attribute for the checkbox, you'll then be able to get access to it on PostBack. However, you have to explicitly look for it in the Attributes collection.

UPDATE: I had originally said it would be the "InputAttributes" collection. I tested and found that I was remembering incorrectly. It's actually the "Attributes" collection that you need to use.

Dim checkb As String
For Each row As GridViewRow In orderGrid.Rows
    Dim chk As CheckBox = CType(row.FindControl("myCheckBox"), CheckBox)
    Dim v as String = chk.Attributes.Item("value")
Next row

An example of defining the value could be as simple as defining it in your markup...

<asp:CheckBox ID="myCheckBox" runat="server" value="Red" />

If you're filling it will values from databinding, then you could use the Eval() function...

<asp:CheckBox ID="myCheckBox" runat="server" value='<%# Eval("myID") %>' />

Then you could also do it via the code behind. Since you have a GridView being used, then in your GridView's RowDataBound event handler, you could get a reference to the CheckBox in that row and define its value there.

CheckBox1.Attributes.Item("value") = "some_value"  ' Could be pulled from whatever data item is tied to your GridView

3 Comments

can you give me an example on how to define the value and what you mean exactly?
I updated my code above with a sample of defining the value. I also corrected the name of the collection I had originally mentioned.
I just read your comment on another answer. Are you trying to get the value, or are you just trying to determine if it's has been checked or not? To determine if it has been checked, you would just look at the "Checked" property. In your code, you'd look at chk.Checked - it will be True/False accordingly.
1

looks to me like you may have to iterate through the cells, rather than the rows; not sure off-hand about vb, in c# it would be something like (CheckBox )(e.Row.Cells[1].FindControl("myCheckBox")) if you did it in the row databound event;

1 Comment

in vb it should be Dim chk As CheckBox = CType(gridView.Rows(i).Cells(j).FindControl("myCheckBox "), CheckBox), or you could have nested foreach loop
0

Try this code this will give selected id in cs code.

<asp:TemplateField HeaderText="All">
   <HeaderStyle Width="3%" HorizontalAlign="Center" VerticalAlign="Middle" />
         <ItemStyle HorizontalAlign="center" VerticalAlign="Middle" />
   <HeaderTemplate>
         <input id="chkAll" type="checkbox" name="chkAll" onclick="javascript: checkall();" />
   </HeaderTemplate>
   <ItemTemplate>
         <input id="chkBox" name="chkBox" type="checkbox" value="<%# DataBinder.Eval(Container.DataItem, "CategoryId") %>" onclick="javascript: checkManual();" />
   </ItemTemplate>
 </asp:TemplateField>

and for javascript function for single selection

function checkManual() {
    var intCheckVal;
    intCheckVal = 1;
    for (intCounter = 0; intCounter < (document.getElementsByName('chkBox').length); intCounter++) {
        if (document.getElementsByName("chkBox")[intCounter].checked == false)
            intCheckVal = 0;
    }
    if (intCheckVal == 1)
        document.getElementById("chkAll").checked = true;
    else
        document.getElementById("chkAll").checked = false;
}

and for check all

function checkall() {
    for (intCounter = 0; intCounter < (document.getElementsByName('chkBox').length); intCounter++) {
        document.getElementsByName("chkBox")[intCounter].checked = document.getElementById("chkAll").checked;
    }
}

Now in cs code on button click event you can get all selected checkbox value using

string MultiIDs = Request.Form["chkBox"].Replace("'", "");

check this,this will work for sure.

Thank you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.