Bellucheese
Bellucheese

Reputation: 3

How do I find the value of a checkbox from a gridview in asp/c#

I have had the most trouble with finding the value of a checkbox. I have searched everywhere and I can't seem to get it to the right value, nothing comes up or I get a NULL reference error. I have checked the other threads/posts and none seem to work.

All I'm trying to do is get the value of a checkbox, but I can't seem to do that.

The information is coming from a database. I can grab the string value but I can't grab the checkbox value.

Anyways, this is the code I used to get ahold of the string value and checkbox value:

//String grabber    
Convert.ToString(gvOrders.SelectedRow.Cells[2].Text);

//Checkbox grabber
Boolean.TryParse(gvOrders.SelectedRow.Cells[11].Text, out bool pep);

or

//Checkbox grabber
Convert.ToBoolean(gvOrders.SelectedRow.Cells[2].Text);

Anyways, please no negativity, I've been struggling to find the value and it just isn't working.

Thanks in advance.

EDIT:

ADDED CODE:

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Convert.ToString(Session["username"]) != "Scott" || Convert.ToString(Session["perms"]) != "admin")
        {
            Response.Redirect("Default.aspx");
        }
        GuestOrderInfo temp = new GuestOrderInfo();
        gvOrders.DataSource = temp.SearchAll();
        gvOrders.DataBind();
    }

    protected void osicOrders(object sender, EventArgs e)
    {
        Int16 row = Convert.ToInt16(gvOrders.SelectedRow.Cells[1].Text);
        Session["row"] = row;
        //Convert to a session to use in a different function.
        Session["fName"] = Convert.ToString(gvOrders.SelectedRow.Cells[2].Text);
        Session["lName"] = Convert.ToString(gvOrders.SelectedRow.Cells[3].Text);
        Session["street"] = Convert.ToString(gvOrders.SelectedRow.Cells[4].Text);
        Session["street2"] = Convert.ToString(gvOrders.SelectedRow.Cells[5].Text);
        Session["city"] = Convert.ToString(gvOrders.SelectedRow.Cells[6].Text);
        Session["state"] = Convert.ToString(gvOrders.SelectedRow.Cells[7].Text);
        Session["zip"] = Convert.ToString(gvOrders.SelectedRow.Cells[8].Text);
        Session["price"] = Convert.ToDouble(gvOrders.SelectedRow.Cells[9].Text);
        Session["size"] = Convert.ToString(gvOrders.SelectedRow.Cells[10].Text);


        Session["pepperoni"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[11].Text, out bool pep);
        Session["sausage"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[12].Text, out bool sau);
        Session["meatball"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[13].Text, out bool mea);
        Session["ham"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[14].Text, out bool hamm);
        Session["peppers"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[15].Text, out bool pepp);
        Session["onions"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[16].Text, out bool onio);
        Session["spinach"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[17].Text, out bool spin);
        Session["pineapple"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[18].Text, out bool pine);
        Session["bbq"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[19].Text, out bool bbqq);
        Session["xcheese"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[20].Text, out bool xch);


        //
        //
        //FIND OUT HOW TO GET THE VALUE OF A CHECKBOX IN GV AND USE THAT VALUE WITHIN SESSION VARIABLES TO UPDATE DATA IN THE UPDATE PAGE THEN MAKE A SEARCH PAGS
        //
        //
        CheckBox cb = (CheckBox)gvOrders.SelectedRow.Cells[11].FindControl("pepperoni");




        selectedID.Text = "Selected: " + Convert.ToString(row);
        selectedInformation.Text = Session["fName"] + " " + Session["lName"] + " Pepp = " + cb.Checked;
        edit.Visible = true;
        delete.Visible = true;
        selectedInformation.Visible = true;
        cancel.Visible = true;
    }


    protected void delete_OnClick(object sender, EventArgs e)
    {
        string buttonText = (sender as LinkButton).Text;


        if (buttonText == "Delete")
        {
            edit.Visible = false;
            delete.Visible = false;
            yes.Visible = true;
            no.Visible = true;
            sure.Visible = true;

        }
        if (buttonText == "Edit")
        {
            Response.Redirect("editOrders.aspx");
        }
        if (buttonText == "Yes")
        {
            GuestOrderInfo temp = new GuestOrderInfo();

            temp.DeleteARecord(Convert.ToInt16(Session["row"]));
            Session.Remove("row");
            Response.Redirect("viewOrders.aspx");
        }
        if (buttonText == "No")
        {
            edit.Visible = true;
            delete.Visible = true;
            yes.Visible = false;
            no.Visible = false;
            sure.Visible = false;
        }
        if (buttonText == "Cancel")
        {
            Response.Redirect("viewOrders.aspx");

        }





    }
}

ORIGINAL HTML:

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="viewOrders.aspx.cs" Inherits="Default2" %>

<asp:Content ID="Content1" ContentPlaceHolderID="title" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="BodyContent" Runat="Server">
    <asp:GridView ID="gvOrders" runat="server" OnSelectedIndexChanged="osicOrders" AutoGenerateSelectButton="True" >
    </asp:GridView>
    <asp:Label runat="server" ID="selectedID"></asp:Label>
    <asp:Label runat="server" ID="selectedInformation" Visible="False"/>
    <asp:LinkButton runat="server" ID="edit" Text="Edit" OnClick="delete_OnClick" Visible="False"/>  <asp:LinkButton runat="server" ID="delete" Text="Delete" Visible="False" OnClick="delete_OnClick"/><asp:LinkButton runat="server" ID="cancel" Text="Cancel" Visible="False" OnClick="delete_OnClick"/><br/>
    <asp:Label runat="server" Text="Are you sure you want to do this?" ID="sure" Visible="False"></asp:Label><br/>

    <asp:LinkButton runat="server" Visible="False" ID="no" Text="No" OnClick="delete_OnClick"/> <asp:LinkButton runat="server" Visible="False" ID="yes" Text="Yes" OnClick="delete_OnClick"/>



    <!-- Make the edit button work along with the delete -->
    <!-- Data validation, design and submit  :^) -->
</asp:Content>

Upvotes: 0

Views: 1844

Answers (2)

Mohamed Najiullah
Mohamed Najiullah

Reputation: 423

It's not clear what value you want to return from the CheckBox. Do you want to get the Checkbox label or selection status?

Anyway instead of trying to get the cell content directly, I think you should instead find the checkbox control like this.

CheckBox cb = (CheckBox)gvOrders.SelectedRow.Cells[2].FindControl("checkboxID");
string checkboxtext = cb.Text; //Gives you the text of the checkbox
bool IsCheckboxChecked = cb.Checked; // Gives you the selection status of the checkbox.

Is this what you're looking for?

Edit: I can see that you have not specified GridView.AutoGenerateColumns Property which means that it defaults to true. What that means is that the layout of the columns is decided by the data that is bound to the grid view. This can cause problems while debugging as the cell index you are giving may change depending on the data that is returned by the data reader. I would advise you to set AutoGenerateColumns to false and manually specify the layout that you want.

You can see an example here

Upvotes: 0

Sunil
Sunil

Reputation: 21396

If you are using a CheckBoxField in your grid view as below, then the code for getting checkbox value is as given in second code snippet.

Checkbox column markup in GridView

 <asp:CheckBoxField DataField="Discontinued" HeaderText="Discontinued" 
         SortExpression="Discontinued" />

Getting the checkbox value in code-behind

bool isChecked = (gvOrders.SelectedRow.Cells[11].Controls[0] as CheckBox).Checked;

However, if you are using a template column in your gridview, then you need to follow different approach that is explained below. In your code-behind,

  • you need to first get the gridview's data row

  • and then find the checkbox control using the ID of the checkbox control you specified in your html markup, which is CheckBox1 in code sample below ( you don't need to bother about getting the cell containing checkbox in this case)

Templated Checkbox Column

<asp:TemplateField HeaderText="CheckBox Column">
<ItemTemplate>
    <asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Eval("Discontinued") %>'  />
</ItemTemplate>

Getting the checkbox value in code-behind

bool isChecked = (gvOrders.SelectedRow.FindControl("CheckBox1") as CheckBox).Checked;

Upvotes: 1

Related Questions