我在aspx文件中设置了gridview,在itemtemplate标记中有一个标签:
<asp:TemplateField HeaderText="Field" SortExpression="Field">
<ItemTemplate>
<asp:Label Font-Size="12px" ID="lblField" runat="server" Text='<%# Bind("DataTableField","{0:N0}") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<div style="text-align: right;">
<asp:Label Font-Size="12px" ID="FieldTotal" runat="server" Font-Bold="true" />
</div>
</FooterTemplate>
</asp:TemplateField>
我没有在aspx文件中创建模板字段,而是尝试从codebehind cs文件中动态创建它们。
到目前为止我所拥有的是:
foreach (DataColumn DC in myDataTable.Columns)
{
TemplateField TF = new TemplateField();
Label myLabel = new Label();
myLabel.Text = bindFromCS();
TF.HeaderText = DC.ColumnName;
TF.SortExpression = DC.ColumnName;
TF.ItemTemplate = new CreateItemTemplate(myLabel);
GridView1.Columns.Add(TF);
}
我没有做的是创建bindFromCS()方法,以便它替换aspx文件中的bind方法。
答案 0 :(得分:0)
有很多方法可以使这种动态变化。
一种方法是必须使用gridview的RowDataBound事件手动为控件赋值。在您的AgentSum_RowDataBound函数中,您可以执行以下操作以动态地为标签赋值
protected void AgentSum_RowDataBound(object sender, GridViewRowEventArgs e)
{
var dataItem = e.Row.DataItem as DataRow; //change this to your domain object type
foreach (Control RowControl in e.Row.Controls)
{
if (RowControl as Label != null) (RowControl as Label).Text = dataItem[(RowControl as Label).Text].ToString();
}
}
第二种方法是你可以在后面的代码中创建一个函数 受保护的字符串GetSumDateValue(DateTime sumDate) { return sumDate.ToString(); //在这里改变你的逻辑 }
并在您的aspx中调用此函数,如下所示
Text='<%# GetSumDateValue(Eval("SumDate")) %>'>
Thrid方法是向域对象iteself添加一个函数
public string FormattedDate
{
get
{
return SumDate.ToString(); // Change your logic here
}
}
将格式化日期绑定到标签
<asp:Label Font-Size="12px" ID="lblSumDate" runat="server" Text='<%# Bind("FormattedDate") %>'></asp:Label>
您可以使用适合您的方法