Home > Net >  How to get checkbox value in ASP.NET
How to get checkbox value in ASP.NET

Time:08-09

<div >
    <input type="checkbox"  ID="customSwitches" />
    <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.

CodePudding user response:

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" />

CodePudding user response:

Well, you can't get the value of the checkbox from the code-behind unless the checkbox control is declared as a server-side control:

<asp:Checkbox id="customSwitches" runat="server" css />

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

  • Related