skip to Main Content
<div class="custom-control custom-switch">
    <input type="checkbox" class="custom-control-input" ID="customSwitches" />
    <label class="custom-control-label" for="customSwitches">Are You Admin?</label>                                   
</div>

The above code is from aspx file

protected void Button1_Click(object sender, EventArgs e)
{
    try
    {
        string username = txtUsername.Text;
        string password = txtPassword.Text;

        bool isAdmin = customSwitches.Checked;
    }
    catch (Exception ex)
    {
        Response.Write(ex.Message);
    }
}

I want to get the checkbox value
But I am getting an error on customSwitches.Checked;
Error: The ‘customSwitches’ doesnot exist in the current context.

3

Answers


  1. Your input with ID="customSwitches" is an html element and not an asp.net checkbox, and as it is missing the runat="server" tag you will not be able to access it by ID in the codebehind.

    Try replacing it with an asp.net checkbox control like this:

    <asp:CheckBox ID="customSwitches" runat="server" CssClass="custom-control-input" />
    Login or Signup to reply.
  2. To determine the value of a checkbox from a code-behind class, the checkbox must be declared as a server-side control (<asp:Checkbox>) with runat="server" attribute instead of a pure HTML element (<input>):

    <asp:Checkbox id="customSwitches" runat="server" cssclass="custom-control-input" />

    Checkboxes don’t return any value other than true or false for the Checked property.

    Login or Signup to reply.
  3. string CheckboxValue = false;
    if(customSwitches.Checked)
    {
    CheckboxValue = true;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search