Iterate DataTable Column And Set Values to Label RRS feed

  • Question

  • User974100899 posted


    Friday, October 4, 2019 9:42 PM


  • User665608656 posted

    Hi LiarLiarPantsOnFire,

    Iterate DataTable Column And Set Values to Label

    Do you want to loop the column names of the DataTable in the code behind to assign label values?

    I have made a simple example, if it does not meet your needs, I hope you can provide more detailed description.

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <form id="form1" runat="server">
                <table style="width: 500px;">
                            <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label></td>
                            <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label></td>
                            <asp:Label ID="Label3" runat="server" Text="Label"></asp:Label></td>
                            <asp:Label ID="Label4" runat="server" Text="Label"></asp:Label></td>
     protected void Page_Load(object sender, EventArgs e)
                    DataTable dt = Bind();
                    for (int i = 0; i < dt.Columns.Count; i++)
                        Label la = (Label)Page.FindControl("Label" + (i+1).ToString());
                        la.Text = dt.Columns[i].ColumnName.ToString();
             public static DataTable Bind()
                string connstring = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
                using (SqlConnection conn = new SqlConnection(connstring))
                    string sql = " select * from Students";
                    SqlDataAdapter ad = new SqlDataAdapter(sql, conn);
                    DataSet ds = new DataSet();
                    return ds.Tables[0];

    Here is the result :

    Best Regards,


    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, October 7, 2019 7:10 AM