有没有办法,如果可以从代码隐藏动态生成ASP.net页面。
示例:
ASP.net:
<div class="hidOverflow setFloatL smallPadLeft" style="width: 45%" runat="server" id="dvLeft">
</div>
<div class="hidOverflow setFloatL smallPadLeft" style="width: 45%" runat="server" id="dvRight">
</div>
代码隐藏:
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
//<div class="hidOverflow smallPad">
//<div class="setFloatL halfWidth vertAlignT">
//<span class="profileLabel">{SQL COLUMN NAME}</span>
//</div>
//<div class="setFloatL vertAlignT">
//<asp:Label ID="lbl1" ClientIDMode="Static" runat="server" Text="{SQL COLUMN VALUE}"></asp:Label>
//</div>
//</div>
//.. 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
//<div class="hidOverflow smallPad">
//<div class="setFloatL halfWidth vertAlignT">
//<span class="profileLabel">{SQL COLUMN NAME}</span>
//</div>
//<div class="setFloatL vertAlignT">
//<asp:Label ID="lbl1" ClientIDMode="Static" runat="server" Text="{SQL COLUMN VALUE}"></asp:Label>
//</div>
//</div>
//.. 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
控件来实现它吗?
答案 0 :(得分:1)
您可以尝试将转发器绑定到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();
}
然后在转发器上:
<ItemTemplate>
<div class="hidOverflow smallPad">
<div class="setFloatL halfWidth vertAlignT">
<span class="profileLabel"><%# Eval("ColumnName") %></span>
</div>
<div class="setFloatL vertAlignT">
<asp:Label ID="lbl2" ClientIDMode="Static" runat="server" Text='<%# GetColumnValue(Eval("ColumnName")) %>'></asp:Label>
</div>
</div>
</ItemTemplate>
这只适用于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<DataColumn>();
var firstHalfColumns = columnCollection.Take(half);
var secondHalfColumns = columnCollection.Skip(half);
repeater1.DataSource = firstHalfColumns;
repeater1.DataBind();
repeater2.DataSource = secondHalfColumns;
repeater2.DataBind();
}