在导出至Excel时移除GridView的编辑和删除列

3
感谢查看我的问题并提供帮助。我有一个用C#构建的asp.net应用程序,其中包含一个简单的网格视图。我有一个按钮可以将网格视图导出到Excel中,这也有效。然而,我的网格视图在第一列有一个编辑链接,在第二列有一个删除按钮。这两个列也会被导出到Excel中。我该如何停止这两列被导出?我尝试了几件事情:
GridView1.Columns.RemoveAt(0);
GridView1.Columns.RemoveAt(1);

并且...

GridView1.Column(0).visible = false;

我尝试了每个方法之后都进行了数据绑定,但它根本不起作用。我会在下面发布我的代码,也许有人可以帮助我!谢谢!

 public void ExportGridToExcel(GridView grdGridView, string fileName)
            {


            Response.Clear();
            Response.AddHeader("content-disposition",
            string.Format("attachment;filename={0}.xls", fileName));
            Response.Charset = "";
            Response.ContentType = "application/vnd.xls";

            StringWriter stringWrite = new StringWriter();
            HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
            grdGridView.RenderControl(htmlWrite);
            GridView1.Columns.RemoveAt(0);
            Response.Write(stringWrite.ToString());
            Response.End();

            GridView1.AllowPaging = false;

    }

GridView的编辑功能被设置为True,删除按钮是一个模板字段,如下:

<Columns>
            <asp:TemplateField>
            <ItemTemplate>
            <asp:Button ID="btnDelete" CommandName="Delete" runat="server"     Text="Delete" CssClass="okbutton" OnClientClick="return confirm('Are you sure you want to delete this entry?');" />
            </ItemTemplate>
            </asp:TemplateField>

你尝试过遍历GridView行并隐藏列单元格吗?请参考此链接https://dev59.com/x2XWa4cB1Zd3GeqPJRbv - Poornima
3个回答

6
您需要隐藏标题行和数据行中的单元格,如下所示:
// Hides the first column in the grid (zero-based index)
GridView1.HeaderRow.Cells[0].Visible = false;

// Loop through the rows and hide the cell in the first column
for (int i = 0; i < GridView1.Rows.Count;i++ )
{
    GridViewRow row = GridView1.Rows[i];
    row.Cells[0].Visible = false;
}

1
GridView1.Columns[6].Visible = false;

1
虽然这段代码片段很受欢迎,可能会提供一些帮助,但如果它包括解释“如何”和“为什么”解决问题,那将会大有改进。请记住,您正在回答未来读者的问题,而不仅仅是现在提问的人!请编辑您的答案以添加解释,并指出适用的限制和假设。 - Toby Speight

0

对于列:

GridName.Columns[index].Visible = false;

对于行:

Gridname.Rows[index].Visible = false;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接