Arif YILMAZ
Arif YILMAZ

Reputation: 5876

How to bind a new datatable to a gridview which already has an old datatable

I have a gridview which is bound to a datatable at runtime. According to the user selection, the datatable's columns can change and then I need to bind the datatable to the same gridview. If the user does so, the system crashes because gridview looks for the same column names.

How can I clean all the gridview and bind a new datatable again and again?

this is how I bind data. everytime column names are changing

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

Upvotes: 1

Views: 2187

Answers (1)

Greg Burghardt
Greg Burghardt

Reputation: 18868

You may be looking for how to re-genarate Grid View columns at run time. This CodeProject.com article might be the ticket: How to create columns dynamically in a grid view.

Some sample ASP Code:

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

And a sample C# method:

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
        });
    }
}

Now to use:

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();

Upvotes: 1

Related Questions