Asp.net Web窗体GridView动态列问题 [英] Asp.net Web Forms GridView Dynamic Column Issue
问题描述
我们有一个具有4.7.2版本的.Net Web窗体应用程序. 当我们以编程方式将列插入GridView组件时,回发后不会呈现TemplateFields. 我们找到了有关该问题的主题.我认为这是一个.Net框架错误.帖子上有反馈网址,但我无法打开该页面.
We have a .Net Web Form application with 4.7.2 version. When we insert column programmaticaly to GridView component, TemplateFields not rendering after postback. We found a topic about that issue. I think this is a .Net framework bug. There is a feedback url on the post but I couldn't open that page.
反馈网址:
主题网址:
https://forums.asp.net/t /1102255.aspx?GridView+Columns+Insert+Problems
示例代码:
Aspx->
Aspx ->
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<asp:GridView ID="TestGrid" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="Col1" DataField="Name" />
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="Col2HeaderLabel" runat="server" Text="Col2"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="Col2CheckBox" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Col3" DataField="Surname" />
</Columns>
</asp:GridView>
<asp:Button ID="TestButton" runat="server" Text="Test" />
</asp:Content>
Aspx.cs->
Aspx.cs ->
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
TestGrid.Columns.Insert(0,new BoundField { HeaderText = "Dynamic Col", DataField = "Description" });
}
protected void Page_Load(object sender, EventArgs e)
{
TestGrid.DataSource = GetList();
TestGrid.DataBind();
}
private List<Info> GetList()
{
List<Info> list = new List<Info>();
list.Add(new Info { Description = "Row 1", Name = "Name 1", Surname = "Surname 1" });
list.Add(new Info { Description = "Row 2", Name = "Name 2", Surname = "Surname 2" });
list.Add(new Info { Description = "Row 3", Name = "Name 3", Surname = "Surname 3" });
return list;
}
}
public class Info
{
public string Name { get; set; }
public string Surname { get; set; }
public string Description { get; set; }
}
推荐答案
@yusuf,您需要将数据源重新绑定到PostBack上的GridView中.将数据gridView.DataSource保存到Session变量中,然后在PostBack上再次进行绑定.这将确保绑定不会丢失.
@yusuf, you need to re-bind the datasource to the GridView on PostBack. Save the data gridView.DataSource into a Session variable and on PostBack do the bind again. This will ensure binding is not lost.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["gvDS"] != null && IsPostBack)
{
gridView1.DataSource = Session["gvDS"];
gridView1.DataBind();
}
else
BindGridView();
}
private void BindGridView()
{
// Your SQL statements go here, etc, then:
gridView1.DataSource = YourDataSetTable;
gridView1.DataBind();
Session["gvDS"] = gridView1.DataSource; // save into Session
}
这篇关于Asp.net Web窗体GridView动态列问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!