"If at first you don't succeed; call it version 1.0" :-Unknown

Pages

Monday, August 16, 2010

Set selectedvalue in RadioButtonList dynamically from database

 Hi frienz,
 for this we need to populate radio-button List from database., we can choose a radio item which we want to selected dynamically before the page rendered.

simple code:

aspx.cs 
protected void Page_Load(object sender, EventArgs e)
        {
          if (!IsPostBack)
                bindRadioList();
        }
private DataSet CreateData()
        {
            DataTable table = new DataTable();
            table.Columns.Add(new DataColumn("OptionID",
 System.Type.GetType("System.String")));
            table.Columns.Add(new DataColumn("Option"
System.Type.GetType("System.String")));
 
            DataRow row1 = table.NewRow();
            row1["OptionID"] = "1";
            row1["Option"] = "A";
 
            DataRow row2 = table.NewRow();
            row2["OptionID"] = "2";
            row2["Option"] = "B";
 
            DataRow row3 = table.NewRow();
            row3["OptionID"] = "3";
            row3["Option"] = "C";
 
            table.Rows.Add(row1);
            table.Rows.Add(row2);
            table.Rows.Add(row3);
 
            DataSet ds = new DataSet();
            ds.Tables.Add(table);
 
            return ds;
 
        }
private void bindRadioList()
        {
            DataSet ds = CreateData();
            RadioButtonList1.DataSource = ds;
            RadioButtonList1.DataTextField = "Option";
            RadioButtonList1.DataValueField = "OptionID";
            RadioButtonList1.DataBind();
 
            if (RadioButtonList1.Items.Count > 0)
                RadioButtonList1.Items[0].Selected = true
                   //you can set a selected items you want.
        }
 
On aspx
  <asp:RadioButtonList ID="RadioButtonList1" runat="server" 
        </asp:RadioButtonList>
 
i think this code helped u 
Have a nice day... 'N happy Coding :)

No comments: