简体   繁体   English

使用dataList循环链接按钮和标签

[英]Looping Linkbutton and Label using dataList

I am trying to search the database using DataList and ItemTemplate . 我正在尝试使用DataListItemTemplate搜索数据库。

I just want to loop the data from database in a linkbutton and a label row by row. 我只想在linkbutton和一行label循环来自数据库的数据。

I am new to this Thanks in Advance 我是新来的,在此先感谢

DataSet ds = new DataSet();
DataTable dt = new DataTable();

dt.Columns.Add(new DataColumn("Description", typeof(string)));
dt.Columns.Add(new DataColumn("Auctionno", typeof(string)));
dt.Columns.Add(new DataColumn("Location", typeof(string)));
SqlCommand cmd = new SqlCommand("select * from Auction_Upload where Keyword = '" + TextBox1.Text + "'", con);

con.Open();
SqlDataReader dr = cmd.ExecuteReader();

if(dr.Read())
{
    DataRow dc = dt.NewRow();
    dc["Description"] = dr["Description"].ToString();
    dc["Auctionno"] = dr["Auctionno"].ToString();
    dc["Location"] = dr["Location"].ToString();
    dt.Rows.Add(dc);
}

DataList1.DataSource = dt;
DataList1.DataBind();

aspx code: aspx代码:

<asp:DataList ID="DataList1" runat="server" Width="600">
    <ItemTemplate> 
        <br /> 
        <asp:LinkButton ID="LinkButton1" Font-Names="Raleway,sans-serif" Font-Size="15" runat="server" Text='<%#Eval("Auctionno") %>' /> 
        <br /> 
        <asp:Label ID="Label1" Font-Size="12" Font-Names="Raleway,sans-serif" runat="server" Text='<%#Eval("Description") %>' />
    </ItemTemplate> 
</asp:DataList> 

As you said in the comments your existing query returns only one row, so this is the reason your DataList shows only one row. 正如您在评论中所说,现有查询仅返回一行,因此这就是您的DataList仅显示一行的原因。

If you want to get all rows from database, change the query and fetch them all 如果要从数据库获取所有行,请更改查询并全部获取

select * from Auction_Upload /*just remove the WHERE clause*/

Everything else is perfectly fine. 其他一切都很好。

change the if to a While and you will get your rows, as you only read one row at a time using datareader.Read() 将if更改为While,您将获得行,因为使用datareader.Read()一次只能读取一行。

while(dr.Read())
{
    DataRow dc = dt.NewRow();
    dc["Description"] = dr["Description"].ToString();
    dc["Auctionno"] = dr["Auctionno"].ToString();
    dc["Location"] = dr["Location"].ToString();
    dt.Rows.Add(dc);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM