In this article I’m going to explain how to bind data to RadioButtonList control in ASP.NET.
RadioButtonList control:
The RadioButtonList control is used to create a group of radio buttons. ListItem element is used to specify the items between opening and closing tags of the RadioButtonList control. RadioButtonList control also support data binding.
Here I’ll show you how to bind list of countries to RadioButtonList control. First we’ve to create table like this
Table design:
Column Name | Data Type |
id | int |
Country | varchar(50) |
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=SPIDER;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();
}
}