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 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择
  • ¥15 这款软件是什么?需要能满足我的需求
  • ¥15 SpringSecurityOauth2登陆前后request不一致