ASP.NET C# DataBind RadioButtonList from DataTable with Multiple Fields

I have been trying to DataBind multiple fields into the RadioButtonList DataTextField from my DataTable, by default this property only accept 1 column using its column name as the primary key. But if I want to concate multiple column, then what do I do? Well after be playing around with this logic, I found that you manually add ListItem to the RadioButtonList, is where you can manual add your DataTextField end results directly into the ListItem.Text property field.

Here my generate DataTable sample data function;

protected static DataTable GetDataSource()
    {
        DataTable table = new DataTable();
        table.Columns.Add("Min", System.Type.GetType("System.Int32"));
        table.Columns.Add("Max", System.Type.GetType("System.Int32"));
        table.Columns.Add("Avg", System.Type.GetType("System.Int32"));

        for (int i = 0; i < 100; i = i + 10)
        {
            DataRow row = table.NewRow();
            row["Min"] = i;
            row["Max"] = i + 9;
            row["Avg"] = (i + 9) / 2;
            table.Rows.Add(row);
        }
        return table;
    }

Now let's see how we apply the text and value to the RadioButtonList, this method me half a day you know;

    protected void Page_Load(object sender, EventArgs e)
    {
        foreach (DataRow row in GetDataSource().Rows)
        {
            ListItem item = new ListItem();
            item.Text = string.Format("{0} - {1}", row["Min"], row["Max"]);
            item.Value = row["Avg"].ToString();
            RadioButtonList1.Items.Add(item);
        }
    }

Here the simple asp.net page;

<%@ 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>ASP.NET C# DataBind RadioButtonList from DataTable with Multiple Fields</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:RadioButtonList ID="RadioButtonList1" runat="server">
        </asp:RadioButtonList>
    </div>
    </form>
</body>
</html>

As you can see that code is pretty simply, but I could not find anything like this on Google. So I like to share my finding, also this method work are DropDownList if you may ask.

  • JD
  • http://www.sarin.mobi Sarin Na Wangkanai
  • berlin raj
  • http://www.sarin.mobi Sarin Na Wangkanai
  • http://www.sarin.mobi Sarin Na Wangkanai