Menu ▼



Posted By :
avatarmrkraju
Total Views : 1050

Asp.net checkbox example

Asp.net checkbox is used to allow user to select multiple options. For example you are offering training for multiple technologies then you can use checkbox to allow select multiple courses. And you can call server side c# code (postback) when the user select or unselect a checkbox. To do that you have to sepecify the AutoPostBack="true" and implement the OnCheckedChanged="chbTutorial_CheckedChanged". Below example will let you know how to implement it.

Reading asp.net checkbox value (selected or not) in c#
Checkobox.Checked property will return true value when the checkbox is checked, other wise it will return false.

chbTutorial.Checked

Calling server side code (checkbox postback event) in asp.net

<asp:CheckBox ID="chbTutorial" runat="server" Text="Opt for online tutorial" AutoPostBack="true"
    OnCheckedChanged="chbTutorial_CheckedChanged" />
<br /><br />
<asp:Label ID="lblMessage" runat="server" Style="color: Green; font-size: 18px; font-weight: bold;"></asp:Label>

protected void chbTutorial_CheckedChanged(object sender, EventArgs e)
{
    if (chbTutorial.Checked == true)
        lblMessage.Text = "You have opeted for online tutorial.";
    else
        lblMessage.Text = "";
}

Example
asp.net checkbox example

ASPX Page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        You can select multiple courses:<br />
        <asp:CheckBox ID="chbAspnet" runat="server" Text="Asp.net" /><br />
        <asp:CheckBox ID="chbCSharp" runat="server" Text="CSharp" /><br />
        <br />
        <br />
        Checkbox postback event:<br />
        <asp:CheckBox ID="chbTutorial" runat="server" Text="Opt for online tutorial" AutoPostBack="true"
            OnCheckedChanged="chbTutorial_CheckedChanged" />
        <br />
        <br />
        <asp:Label ID="lblMessage" runat="server" Style="color: Green; font-size: 18px; font-weight: bold;"></asp:Label>
    </div>
    </form>
</body>
</html>

CS Page

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

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void chbTutorial_CheckedChanged(object sender, EventArgs e)
    {
        if (chbTutorial.Checked == true)
            lblMessage.Text = "You have opeted for online tutorial.";
        else
            lblMessage.Text = "";
    }
}






comments powered by Disqus


Search dotnetlearners.com