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.


Kick It on DotNetKicks.com

  • JD

    I was looking at your code and may be I missing something, but why would you don’t something like this

    radiobuttonlist1.datasource = table
    radiobuttonlist1.datafieldtext = “avg”
    radiobuttonlist1.datafieldvalue = “min or max”
    radiobuttonlist1.databind

    I know there is a way to have the value be a combination of the two fields from your datatable, but I think this would be good for what you are looking to do.

  • http://www.sarin.mobi Sarin Na Wangkanai

    interesting, couldn’t find anything anywhere on google. i’ll give it a go later

    thanks

  • berlin raj

    hi,
    am develpoing a program in ASP.NET which am opening one database connection and retrieve one table(table 1) and them am closing that connection .again am opening another connection and retrieving one table (table 2)using the same query.now i would like to add both the tables using arrayllist.for ex,

    table 1 table 2
    name age salary name age salary
    white 10 1000 henry 10 2000
    woods 15 2000 white 10 2000

    now the output should be..

    table 3
    name age salary
    white 20 3000
    woods 15 2000
    henry 10 2000


    i could connect both the databases separately and retrieve the values using excel sheet.i found difficuly in combining both the table..
    can you please help me out in achiving this

    Pls send that coding in my mail id

  • http://www.sarin.mobi Sarin Na Wangkanai

    Hi, i was looking at your question and came up with this solution, their could be something simpler, but that is for you to explorer.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Collections;
    using System.Data;

    namespace JoinTable
    {
    class Program
    {
    static void Main(string[] args)
    {
    DataTable table1 = CreateTable(new sRow[2]{
    new sRow(){ Name=”White”, Points=10, Salary =1000},
    new sRow(){ Name=”Woods”, Points=15, Salary = 2000}
    });
    DataTable table2 = CreateTable(new sRow[2]{
    new sRow(){ Name=”Henry”, Points=10, Salary =2000},
    new sRow(){ Name=”White”, Points=15, Salary = 2000}
    });

    ArrayList list = new ArrayList();
    // add table1 to list
    foreach (DataRow row in table1.Rows)
    list.Add(new sRow()
    {
    Name = row["Name"].ToString(),
    Points = int.Parse(row["Points"].ToString()),
    Salary = int.Parse(row["Salary"].ToString())
    });

    // add table2 to list
    int count = list.Count;
    foreach (DataRow row in table2.Rows)
    for (int i = 0; i < count; i++)
    if (((sRow)list[i]).Name == row["Name"].ToString())
    {
    sRow ThisListRow = (sRow)list[i];
    ThisListRow.Points += int.Parse(row["Points"].ToString());
    ThisListRow.Salary += int.Parse(row["Salary"].ToString());
    list.RemoveAt(i);
    list.Add(ThisListRow);
    break;
    }
    else
    {
    list.Add(new sRow()
    {
    Name = row["Name"].ToString(),
    Points = int.Parse(row["Points"].ToString()),
    Salary = int.Parse(row["Salary"].ToString())
    });
    break;
    }
    foreach (sRow row in (sRow[])list.ToArray(typeof(sRow)))
    Console.WriteLine(“{0}\t{1}\t{2}”, row.Name, row.Points, row.Salary);
    Console.ReadKey(true);
    }

    protected static DataTable CreateTable(sRow[] aTable)
    {
    DataTable dTable = new DataTable();
    dTable.Columns.Add(“Name”, typeof(string));
    dTable.Columns.Add(“Points”, typeof(int));
    dTable.Columns.Add(“Salary”, typeof(int));

    DataRow row;
    foreach (sRow _row in aTable)
    {
    row = dTable.NewRow();
    row["Name"] = _row.Name;
    row["Points"] = _row.Points;
    row["Salary"] = _row.Salary;
    dTable.Rows.Add(row);
    }
    return dTable;
    }
    }
    struct sRow{
    private string name;
    private int points;
    private int salary;

    public string Name { get { return name; } set { name = value; } }
    public int Points { get { return points; } set { points = value; } }
    public int Salary { get { return salary; } set { salary = value; } }
    }
    }

  • http://www.sarin.mobi Sarin Na Wangkanai

    Hi! Raj,

    You would like to modify the data table1 with table2, not join then them into a new table3 right?

    Why don’t you do something like;

    For(int i = 0; i < table1.Count; i++)
    For(int j = 0; j< table2.Count; j++)
    If(table1.Rows[i][“Name”] == table.Rows[j][“Name”]
    {
    Table1.Rows[i][“Leave”] += table2.Rows[j][“Leave”];
    Table1.Rows[i][“Salary”] += table2.Rows[j][“ Salary”];
    }
    else
    table1.Rows.Add(table.Rows[j];