简体   繁体   中英

How to get checkbox value in ASP.NET

<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.

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

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" cssclass="custom-control-input" />

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

string CheckboxValue = false;
if(customSwitches.Checked)
{
CheckboxValue = true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM