如何生成动态标签并使用列名和值作为文本

有没有办法,如果可以从代码隐藏动态生成ASP.net页面。

例:

ASP.net:

代码隐藏:

 using (SqlConnection conn = new SqlConnection(gloString)) { try { strQuery = @""; SqlDataAdapter da = new SqlDataAdapter(strQuery, conn); DataSet myDataSet = new DataSet(); da.Fill(myDataSet); //dynamically generate label with the SQL column name as the Text //dynamically generate label with the SQL column value as the text //
//
//{SQL COLUMN NAME} //
//
// //
//
//.. more .. stop at the 1/2 mark of the count for the dataset and add it to the "dvLeft" div // STOP... //dynamically generate label with the SQL column name as the Text //dynamically generate label with the SQL column value as the text //
//
//{SQL COLUMN NAME} //
//
// //
//
//.. more .. continue from the 1/2 mark of the count for the dataset and add it to the "dvRight" div } catch (SqlException) { } }

我希望它是动态的,所以我所要做的就是更改SQL查询,并相应地生成标签。

我最有可能使用asp:Repeater控件来实现它?

您可以尝试将转发器绑定到Datatable ColumnCollection:

 private DataTable _dataTable; public void LoadRepeater() { //load dataset _dataTable = myDataSet.Tables[0]; repeater.DataSource = _dataTable.Columns; repeater.DataBind(); } public string GetColumnValue(string columnName) { return _dataTable.Rows[0][columnName].ToString(); } 

然后在转发器上:

  
<%# Eval("ColumnName") %>

这只适用于DataTable上有一行的情况。

如果您有更多行,则可能必须为行维包含额外的转发器。

————————————————– —————-

要拆分列,您可以执行以下操作(未经测试):

 private void LoadRepeater() { //load dataset _dataTable = myDataSet.Tables[0]; int columnCount = _dataTable.Columns.Count; int half = (int)columnCount/2; var columnCollection = _dataTable.Columns.OfType(); var firstHalfColumns = columnCollection.Take(half); var secondHalfColumns = columnCollection.Skip(half); repeater1.DataSource = firstHalfColumns; repeater1.DataBind(); repeater2.DataSource = secondHalfColumns; repeater2.DataBind(); }