You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何避免GridView列重复显示?自定义列替代数据集列

解决GridView同时显示自动生成列和自定义列的问题

问题根源是GridView默认的AutoGenerateColumns属性为true,绑定DataSet时会自动根据数据源的列生成对应列,再加上你手动添加的自定义列,就会出现重复显示的情况。

最直接高效的解决方法是禁用自动生成列,只保留你自定义的列:

在绑定数据源前,添加一行代码设置AutoGenerateColumns为false,这样GridView只会渲染你手动定义的列,不会自动生成DataSet的列。

修改后的完整代码如下:

string connectionFromConfiguration = WebConfigurationManager.ConnectionStrings["Directors"].ConnectionString;
DataSet dsCustomers = new DataSet();
using (SqlConnection con = new SqlConnection(connectionFromConfiguration))
{
    using (SqlCommand cmd = new SqlCommand("spQryAllusers"))
    {
        cmd.CommandType = System.Data.CommandType.StoredProcedure;
        cmd.Connection = con;
        con.Open();
        using (SqlDataReader sdr = cmd.ExecuteReader())
        {
            dsCustomers.Tables.Add("Customers");
            dsCustomers.Tables[0].Load(sdr);
        }
        con.Close();

        HyperLinkField hlId = new HyperLinkField
        {
            DataTextField = "ID",
            HeaderText = "Action"
        };
        gvUsers.Columns.Add(hlId);
        BoundField email = new BoundField
        {
            HeaderText = "Email",
            DataField = "EmailAddress"
        };
        gvUsers.Columns.Add(email);

        // 关键:禁用自动生成列,只显示自定义列
        gvUsers.AutoGenerateColumns = false;
        gvUsers.DataSource = dsCustomers;
        gvUsers.DataBind();
    }
}

如果一定要在绑定后处理(不推荐,多了不必要的渲染步骤),可以在DataBind()后遍历列并移除自动生成的列,但自动生成列和自定义列没有明显标识,实现起来更繁琐,不如直接禁用自动生成列来得简单。

内容的提问来源于stack exchange,提问作者user3849334

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 00:24:32