【问题标题】:How to bind a new datatable to a gridview which already has an old datatable如何将新数据表绑定到已有旧数据表的网格视图
【发布时间】:2014-03-12 16:57:58
【问题描述】:

我有一个在运行时绑定到数据表的 gridview。根据用户的选择,数据表的列可以改变,然后我需要将数据表绑定到同一个gridview。如果用户这样做,系统会崩溃,因为 gridview 会查找相同的列名。

如何清理所有的gridview并一次又一次地绑定一个新的数据表?

这就是我绑定数据的方式。每次列名都在变化

DataTable result = dt_to_result_bolge_kiyaslama(dt);
gv_kiyaslama.DataSource = result;
gv_kiyaslama.DataBind();

【问题讨论】:

  • 最简单的方法就是重新初始化gridview还是我误解了什么?
  • 您是否在 gridview 中使用了自动生成的列,还是没有?
  • 你能告诉我你的代码吗?

标签: c# asp.net gridview datatable


【解决方案1】:

您可能正在寻找如何在运行时重新生成网格视图列。这篇 CodeProject.com 文章可能是票:How to create columns dynamically in a grid view。

一些示例 ASP 代码:

<asp:GridView ID="MyGrid" runat="server" AutoGenerateColumns="false">
    <Columns />
</asp:GridView>

还有一个示例 C# 方法:

public void RegenerateColumns(GridView grid, DataTable data, IDictionary<string, string> columnText)
{
    grid.Columns.Clear();

    foreach (DataColumn col in data.Columns)
    {
        grid.Columns.Add(new BoundField()
        {
            DataField = col.ColumnName,
            HeaderText = columnText.ContainsKey(col.ColumnName)
                ? columnText[col.ColumnName]
                : col.ColumnName
        });
    }
}

现在使用:

DataTable table = new DataTable();
table.Columns.Add(...); // add "NAME" column
table.Columns.Add(...); // add "DESCRIPTION" column

// Create mapping of column names to text visible to the user
Dictionary<string, string> cols = new Dictionary<string, string>()
{
    { "NAME", "Name" },
    { "DESCRIPTION", "Description" }
};

// Call method:
RegenerateColumns(MyGrid, table, cols);

// Rebind the data to the grid
MyGrid.DataSource = table;
MyGrid.DataBind();

【讨论】:

  • 这解释了如何动态绑定网格。我可以成功地做到这一点,但是如果我更改列名并将其再次绑定到同一个网格,那么它会崩溃,因为它会查找旧的列名
  • 那篇文章确实解释了你想要什么。我会更新我的答案。
  • 这不是好方法。我期待找到一个类似 clear() 的函数
  • 有一个clear函数:GridView.Columns.Clear() -- 清除网格上的列。
  • 我知道,但如果我做 clear(),它不接受第二个数据表的列
猜你喜欢
  • 2011-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-20
相关资源
最近更新 更多