namasayadin namasayadin - 7 months ago 11
SQL Question

The looping only shows one data

I am new to

C#
and currently studying myself. In my project what I would like to do is to take 10 data from a
table
and to be show in a loop. For example if it has 10 data, so all the data will be shown in the
default.aspx
page. Currently my code can only display the first row and loop it 10 time. Below is my sample.

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


}
}


}

Below is my default.aspx page..

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




May I know what I am doing wrong. Thank you in advance.

Answer

You are setting the "Text" property of same label 10 times. It is being overwritten on every iteration of the loop. You should append the value of column from database to label. Modify code as below:

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