C# 清除带有静态列和动态列的栅格
我有一个网格,通过aspx页面在模板字段中添加了几列C# 清除带有静态列和动态列的栅格,c#,asp.net,gridview,C#,Asp.net,Gridview,我有一个网格,通过aspx页面在模板字段中添加了几列 <asp:TemplateField> <ItemTemplate> <asp:LinkButton ID="lnkBtnDown" runat="server" CommandName="Download" Text="Download"></asp:LinkButton> <asp:LinkButto
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkBtnDown" runat="server" CommandName="Download" Text="Download"></asp:LinkButton>
<asp:LinkButton ID="LnkBtnMan" runat="server" CommandName="Manual" Text="Manual"
Style="margin-left: 10px"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
在每个搜索按钮的开头,单击事件I刷新网格
dgvSearchResults.DataSource = null;
dgvSearchResults.DataBind();
dgvSearchResults.Columns.Clear();
但这会清除所有列,包括我在aspx页面中绑定的列..正如预期的那样。如果我不清除它们,搜索结果中的列就会不断堆积
有没有办法只清除动态绑定的列?如果您知道在aspx页面中添加了多少列以及动态添加了多少列,您可以这样做
//if total added in aspx page is 2, first one is in index 0, second in index 1
dgvSearchResults.Columns.RemoveAt(2); // this will remove the 3rd column
dgvSearchResults.Columns.RemoveAt(3); // this will remove the 4th columns
// you can continue till column x
一个选项是使用dgvSearchResults GridView。在这种情况下,每次回发都需要将dgvSearchResults与数据绑定。如果不绑定,动态添加的列将自动删除(而不是持久化)
这种情况会发生,因为在您的情况下,动态添加的数据(以及列)在隐藏元素(viewstate)中保持回发到回发
因此,这将成为:
private void Page_Load(object sender, EventArgs e)
{
if(IsPostBack) // If postback, then bind GridView with previous search result
{
dgvSearchResults.DataSource = Session["dgvSearchResultsData"];
dgvSearchResults.DataBind();
}
}
private void generateSearchGrid(DataTable dt)
{
// ...
Session["dgvSearchResultsData"] = dt; // Save result into session
dgvSearchResults.DataSource = dt;
// ...
}
ASPX:
。。。
private void Page_Load(object sender, EventArgs e)
{
if(IsPostBack) // If postback, then bind GridView with previous search result
{
dgvSearchResults.DataSource = Session["dgvSearchResultsData"];
dgvSearchResults.DataBind();
}
}
private void generateSearchGrid(DataTable dt)
{
// ...
Session["dgvSearchResultsData"] = dt; // Save result into session
dgvSearchResults.DataSource = dt;
// ...
}
<asp:GridView EnableViewState="false"> ... </GridView>