Monday 14 October 2013

How to bind data to RadioButtonList control in ASP.NET using C#

Designer source code:

<%@ 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>
    <asp:radiobuttonlist ID="rblCountry" runat="server"></asp:radiobuttonlist>
    </div>
    <div>
     <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" /><br />
     <asp:Label ID="lblValue" runat="server"></asp:Label>
    </div>
    </form>
</body>
</html>
  

C#-code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient; 
public partial class _Default : System.Web.UI.Page
{
    SqlConnection conn = new SqlConnection("Data Source=Gangwar;Initial Catalog=Demo;Integrated Security=True");
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindList();
        }
    } 
    private void BindList()
    {
        DataSet ds = new DataSet();
        string cmdstr = "select id,country from Country";
        SqlDataAdapter adp = new SqlDataAdapter(cmdstr, conn);
        adp.Fill(ds);
        rblCountry.DataSource = ds;
        rblCountry.DataTextField = "country";
        rblCountry.DataValueField = "id";
        rblCountry.DataBind();
    } 
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        lblValue.Text = rblCountry.SelectedItem.ToString(); 
    }

}

No comments:

Post a Comment