简体   繁体   中英

Looping Linkbutton and Label using dataList

I am trying to search the database using DataList and ItemTemplate .

I just want to loop the data from database in a linkbutton and a label row by row.

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:

<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.

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()

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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