Binding data into Radiobuttonlist in asp.net using c#

In this article, I would like to  show you how to create Dynamic Radiobuttonlist in asp.net by loading its listitem from  a table field in SQL Server 2008. In this case, I want to binding data into radiobuttonlist on load page from table field "country" of a table  tblcountry.

Sample Table: 

Sample table
Figure 1:  sample table

 Code Design:

<asp:RadioButtonList ID="RadioButtonList2" runat="server"></asp:RadioButtonList>

Code behind:

Import two namespaces 
//import these two namespaces :System.Data and System.Data.SqlClient  to use  .NET //Framework Data Provider for SQL Server
using System.Data;
using System.Data.SqlClient;
//Event page load
     protected void Page_Load(object sender, EventArgs e)
    {
         if (!IsPostBack) {
             DataTable dt = new DataTable();
             dt = Loadlist();
             RadioButtonList2.DataSource = dt;
             RadioButtonList2.DataValueField = "country";
             RadioButtonList2.DataBind();
          }
    }


    public DataTable Loadlist()
    {
      SqlConnection con = new SqlConnection();
      string str;
      string sql;

      str="Server=UBEE_THAROTH ;Database=Drink;uid=sa;pwd=123;";
      sql = "Select * from tblcountry order by country asc";

      con.ConnectionString = str;
      con.Open();

      SqlDataAdapter da = new SqlDataAdapter(sql,con);
      DataTable dt = new DataTable();
      da.Fill(dt);

      if(dt.Rows.Count>0){
         return dt;
      }
      else {
         return null;
      }           
  }

Result:

country radiobuttonlist
Figure 2:  Country radiobuttonlist


Binding data into Radiobuttonlist in asp.net using c# Binding data into Radiobuttonlist in asp.net using c# Reviewed by BeiLover on 1:46 PM Rating: 5

No comments:

Powered by Blogger.