如何在Asp.net WebForm中使用ListView

时间:2012-03-15 02:24:12

标签: asp.net sql

我有这个代码,我只能在文本框中显示它

<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{

    string connect =  ConfigurationManager.ConnectionStrings["TDBSConnectionString"].ConnectionString;

    string query = "SELECT news, news_date FROM [IBSI].[dbo].[ibsi.news]";

    if (query != null)
    {
        using (SqlConnection conn = new SqlConnection(connect))
        {
             using (SqlCommand cmd = new SqlCommand(query, conn))
             {

              conn.Open();
              SqlDataReader rdr = cmd.ExecuteReader();
              if (rdr.HasRows)
              {
                   while (rdr.Read())
                   {
                      Textbox1.Text=rdr["news"].ToString();
                   }
              }
         }
    }
}
else 
{
      Response.Write("<p>No customer selected</p>"); 
}

}
</script

我只在这里显示

<asp:TextBox ID="TextBox1" runat="server" Height="168px" TextMode="MultiLine" 
                        Width="303px"></asp:TextBox>

但是在我的数据库中我有超过1个数据,所以我需要一个listview来显示这些项目。 请帮我说明如何做到这一点。

1 个答案:

答案 0 :(得分:1)

Repeater的示例HTML

<asp:Repeater ID="rpt" runat="server" >
    <HeaderTemplate>
        <table>
            <tr>
                <td id="header" style="background:green;" runat="server">
                    textBox
                </td>
            </tr>
    </HeaderTemplate>
    <ItemTemplate>
        <tr>
            <td>
                <asp:TextBox ID="ed" runat="server" Text='<%#Eval("news") %>' autocomplete="off"></asp:TextBox>
            </td>
        </tr>
    </ItemTemplate>
    <FooterTemplate>
        </table>
    </FooterTemplate>
</asp:Repeater>

示例代码

public class News
{
    public String news;
}
List<News> Listnews = new List<News>();
using (SqlConnection conn = new SqlConnection(connect))
{
    using (SqlCommand cmd = new SqlCommand(query, conn))
    {

        conn.Open();
        SqlDataReader rdr = cmd.ExecuteReader();
        if (rdr.HasRows)
        {
            while (rdr.Read())
            {
                Listnews.Add(new News { news = rdr["news"].ToString() });
            }
        }
    }
}

rpt.DataSource = Listnews;
rpt.DataBind();