代码之家  ›  专栏  ›  技术社区  ›  Salman Arshad

ASP.NET在循环中添加控件

  •  2
  • Salman Arshad  · 技术社区  · 15 年前

    对不起,这真是一个无意义的问题,但请理解我没有太多的ASP.NET经验。我需要做的就是:

    1)打开以下SQL查询:

    SELECT myid FROM mytable
    

    2)对于每个记录,生成此HTML片段:

    <a href="#mynameanchor" onClick="myfunction( '__myid comes here__' );"><img src="http://someurl/__myid comes here as well__/small.png" /></a>
    

    我很容易使用经典的ASP <% do until recordset.eof ... loop %> 样式循环,但我需要它是ASP.NET样式,可能在页面加载事件中执行操作,并使用内部ASP.NET控件。

    3 回复  |  直到 15 年前
        1
  •  4
  •   Gabriel McAdams    15 年前

    使用中继器控制。在itemtemplate中,您可以为查询返回的每个记录放置希望生成的任何内容。

    http://articles.sitepoint.com/article/asp-net-repeater-control

        2
  •  3
  •   Hiyasat    15 年前

    将此添加到ASPX页源中

       <td id="urLink" runat="server">
    
       </td>
    

    在页面加载事件中添加此项

     SqlConnection con = new SqlConnection();
     con.connectionstring = "your connection database";
     SqlDataReader reader;
     SqlCommand command = new SqlCommand(con);
     command.Commandtext = "SELECT myid FROM mytable";
     command.CommandType = CommandType.Text;
     reader = command.ExecuteReader();
     while(reader.Read())
     {
          urLink.innerHTML += "<a   href="#mynameanchor" onClick="myfunction( " + reader["myid"].tostring() + " );">
        <img src="http://someurl/" + reader["myid"].tostring() + "/small.png" /></a>";
     }
    
        3
  •  2
  •   Ariel    15 年前

    看起来onclick是一个javascript事件,这意味着您可以将HTML标记写出一个字符串,然后将其全部附加到一个文本控件中。请记住使用StringBuilder:)

    下面是一个非常基本的例子:

    // get data from database and into a reader before
    
    StringBuilder links = New StringBuilder();
    
    while(reader.read())
    {
        links.appendFormat("<a HREF='id_{0}'>{0}</a>", reader["ID"]);
    }
    
    ltlLinks.Text = links.ToString();