Wednesday, 5 June 2013

Bind Radiobutton list From DAtabase

How to Bind/Fill RadioButtonList from Sql server table in asp.net(C#, VB)




Introduction: In the previous example I explained How to fill DropDownList from Sql server database in asp.net and How to Fill CheckBoxList from Sql Server table in asp.net(C#,VB). Now in this article i will explain how to fill/Bind RadioButtonList fromSql Server Database table using asp.net. Let's understand by an example.

Fill RadioButtonList example in asp.net
  • Create a table in sql server as shown in Fig below  and name it QUALIFICATION_TABLE:

Bind RadioButtonList example in asp.net
  • Create a connectionstring in the web.config file under configuration tag as:

<connectionStrings>
    <add name="ConStr" connectionString="Data Source=LALIT;Initial Catalog=MyDataBase;Integrated Security=True"/>
  </connectionStrings> 
  • Now in design page(.aspx) place a RadioButtonList control as :

<fieldset style="width:250px;">
            <legend>Fill RadioButtonList Example in asp.net</legend>
             <asp:RadioButtonList ID="rblQualification" runat="server" RepeatColumns="3"RepeatDirection="Horizontal"></asp:RadioButtonList>   
        </fieldset>

C#.NET Code
  • In the code behind file (.aspx.cs) write the code as:

First include following namespaces:
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            FillQualifications();
        }

    }
    private void FillQualifications()
    {
        SqlConnection con = newSqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString);
        SqlCommand cmd = new SqlCommand("Select * from Qualification_Table", con);
        SqlDataAdapter adp = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        adp.Fill(dt);
        rblQualification.DataSource = dt;
        rblQualification.DataTextField = "Qualification";
        rblQualification.DataValueField = "Qualification_ID";
        rblQualification.DataBind();
    }

No comments:

Post a Comment