dreamMyDream2014 2013-11-03 19:31
浏览 130
已采纳

ASP.NET循环遍历datatable列并为每个项写入一个复选框

I'm brand new to ASP.NET with intermediate C# level, and previously I wrote a PHP project. I'm now stuck trying to get a similar effect in ASP.NET.

What I'm using: The project is C# ASP.NET Empty web application. I'm using Visual Studio 2010 with SP1. MSSQL 2008 R2

What I want to do is add HTML code using a foreach into the ASP file, specific content area.

This is what I would do in php:

foreach ($library as $book)
{
    print "<a href=\"bookpage.php?id=".$book[book_id]"";      
    print "<h3>".$book[book_author]."</h3>";
    print " <p>".$book[book_blurb]."</p>";
}

This is what I've tried in ASP:

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">

    <asp:RadioButtonList ID="RadioButtonPizzaList" runat="server">
            <asp:ListItem Text="Margerita" />
            <asp:ListItem Text="Hawaain" />
            <asp:ListItem Text="Meat Supreme" />
    </asp:RadioButtonList>
</asp:Content>

But instead of hardcoding, I want to add a listitem for each pizza thats been retrieved from the database, the names of pizza are stored in an array. How would I use a loop and add an HTML line like what I did in above PHP example?

  • 写回答

2条回答 默认 最新

  • dp152153 2013-11-03 20:47
    关注

    I assume that your pizza list has two columns that Id and PizzaName.
    And you have a method that getting pizza list from db as named GetList in Pizza class.
    Firstly you should add two attributes in aspx side to your radio button list control. They are DataValueField and DataTextField. These attributes required for data binding.

    Aspx Side

     <asp:RadioButtonList ID="RadioButtonPizzaList" DataValueField="Id" DataTextField="PizzaName"  runat="server">            
     </asp:RadioButtonList>
    

    Code behind Side

    private void FillPizzaList()
        {
            DataTable dtList = Pizza.GetList();     
    
            this.RadioButtonPizzaList.DataSource = dtList;
            this.RadioButtonPizzaList.DataBind();
        }
    

    If you want to get selected item value you can get with this code

    this.RadioButtonPizzaList.SelectedValue
    

    Note: If you fill radiobutton list in page load event, do not forget check is postback.

    if ( !IsPostBack )
     this.FillPizzaList();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序