drquinn
drquinn

Reputation: 477

Create multiple RadioButtonLists in ASP.NET from a single table in SQL Server using C#

I would like to use ASP.net, C# and SQL to display a list of games with radio buttons like below (the x is the radio). One team can be selected for each game.

game 1:   x team 4   x team 2
game 2:   x team 6   x team 1
game 3:   x team 5   x team 3

The game list is stored in a table in an SQL database. So far, I can pull all teams into one big RadioButtonList. I cannot figure out how to create multiple RadioButtonList controls from this single table of games. Does anyone know how this can be accomplished - or reference to an example / tutorial that accomplishes something like this?

Upvotes: 0

Views: 2033

Answers (1)

Raymund
Raymund

Reputation: 7892

Use a listview for the different games and radiobuttonlist for the items

like such

<asp:ListView ID="ListView1" runat="server" onitemdatabound="ListView1_ItemDataBound">
    <ItemTemplate>
        <asp:Label runat="server" ID="txtGame" Text='<%# Bind("GameName") %>'></asp:Label><br />
        <asp:HiddenField ID="hdnGameID" runat="server" Value='<%# Bind("GameID") %>'/>
        <asp:RadioButtonList runat="server" ID="rblTeam" DataTextField="TeamName" DataValueField="TeamID">
        </asp:RadioButtonList>
    </ItemTemplate>
</asp:ListView>

then on your code behind

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        var oGame = from g in myDB.Game
                    group g by g.GameName into result
                    select new { GameID = result.Key, GameName = result };

        ListView1.DataSource = oGame;
        ListView1.DataBind();
    }
}

protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
    HiddenField hdnGameID = (HiddenField)e.Item.FindControl("hdnGameID");
    RadioButtonList rblTeam = (RadioButtonList)e.Item.FindControl("rblTeam");

    var oTeam = from t in myDB.Game
                where t.GameID == hdnGameID.Value
                select t;

    rblTeam.DataSource = oTeam;
    rblTeam.DataBind();
}

Upvotes: 2

Related Questions