循环只显示一个数据

The looping only shows one data

我是 C# 的新手,目前正在自学。在我的项目中,我想做的是从 table 中获取 10 个数据并循环显示。比如有10条数据,那么所有的数据都会显示在default.aspx页面。目前我的代码只能显示第一行并循环 10 次。下面是我的示例。

namespace CRM_Attachment

public partial class _Default : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Sample"].ConnectionString;
        SqlConnection con = new SqlConnection(connectionString);

        SqlCommand com;
        con.Open();
        string str = "SELECT TOP 10 FILE_NAME FROM FILE";
        com = new SqlCommand(str, con);
        SqlDataReader reader = com.ExecuteReader();


        //if (reader.HasRows)
       //{
            while (reader.Read())
            {
                labelname1.Text = reader["FILE_NAME"].ToString();
            }
        //}

        reader.Close();
        con.Close();


    }
 }

}

下面是我的 default.aspx 页面..

<body>
<form id="form1" runat="server">
<% for (int i=0;i<10;i++) {%>
<div>
<asp:Label ID="labelname1" runat="server" Text="Label"></asp:Label>
</div>
<%}%>
</form>

请问我做错了什么。提前谢谢你。

您正在设置相同标签的 "Text" 属性 10 次。它在循环的每次迭代中都被覆盖。您应该将列的值从数据库附加到标签。修改代码如下:

labelname1.Text += reader["FILE_NAME"].ToString();