locked
Iterate DataTable Column And Set Values to Label RRS feed

  • Question

  • User974100899 posted

    XXXXXXXXXx

    Friday, October 4, 2019 9:42 PM

Answers

  • 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">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <table style="width: 500px;">
                    <tr>
                        <td>
                            <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label></td>
                        <td>
                            <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label></td>
                        <td>
                            <asp:Label ID="Label3" runat="server" Text="Label"></asp:Label></td>
                        <td>
                            <asp:Label ID="Label4" runat="server" Text="Label"></asp:Label></td>
                    </tr>
                </table> 
            </div>
        </form>
    </body>
    </html>
     protected void Page_Load(object sender, EventArgs e)
            {
                if(!IsPostBack)
                {
                    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))
                {
                    conn.Open();
                    string sql = " select * from Students";
                    SqlDataAdapter ad = new SqlDataAdapter(sql, conn);
                    DataSet ds = new DataSet();
                    ad.Fill(ds);
                    conn.Close();
                    return ds.Tables[0];
                }
            }

    Here is the result :

    Best Regards,

    YongQing.

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