Last post Oct 07, 2019 07:10 AM by Yongqing Yu
Member
46 Points
124 Posts
Oct 04, 2019 09:42 PM|LiarLiarPantsOnFire|LINK
XXXXXXXXXx
Contributor
3720 Points
1043 Posts
Oct 07, 2019 07:10 AM|Yongqing Yu|LINK
Hi LiarLiarPantsOnFire,
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.
Member
46 Points
124 Posts
Iterate DataTable Column And Set Values to Label
Oct 04, 2019 09:42 PM|LiarLiarPantsOnFire|LINK
XXXXXXXXXx
Contributor
3720 Points
1043 Posts
Re: Iterate DataTable Column And Set Values to Label
Oct 07, 2019 07:10 AM|Yongqing Yu|LINK
Hi LiarLiarPantsOnFire,
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.
Here is the result :
Best Regards,
YongQing.
Please remember to click "Mark as Answer" the responses that resolved your issue.
If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.