DataGrid exchanging a DataSource, but Columns are added...

A

Alexander

Hi, I am using a DataGrid and assign a DataTable as a DataSource to
it:

void ShowData()
{
DataTable myNewDataTable = new DataTable();
... // fill table
this.m_DataGrid1.DataSource = myNewDataTable;
this.Refresh();
}

I create the DataTable from the scratch of some XML data and then
simply assign it. This works perfectly, the table with all the columns
is displayed.

If I call the function a second time, and assign a new DataTable as a
DataSource, the new table is added to the grid instead of replacing
the old one. So if the old table had columns 1, 2 and 3 and the new
table 98, 99, the result is a grid with the columns 1, 2, 3, 98, 99.

I already debugged, to make sure if the new DataTable really has only
2 columns and that afterwards the new DataSource of the DataGrid has
only 2 columns, too. But displayed are 5 columns afterwards...

Is there a special trick to replace the DataSource?
 
D

Dmitriy Lapshin [C# / .NET MVP]

Hi,

If it's a WinForms DataGrid, try using the SetDataBinding method instead.
 
P

Paul

If I understand correctly, you are going through the same problem I had recently.
here is some code.
all you need to do is to create a new table.

private void LoadData(System.Data.DataTable dt)
{
try
{
this.dataSet.Tables.Clear();
}
catch{}

this.dataTable = null;
this.dataTable = dt.Copy();
this.dataSet.Tables.Add(dataTable);
this.dataSet.AcceptChanges();

string member = dataTable.TableName;
this.dataGrid1.SetDataBinding(dataSet,member);
this.dataGrid1.CaptionText = member;
}

Hope this will help
Paul
 
A

Alexander

Thanks Paul, that brought me near to the solution.

I was not aware of the internal structure of the DataSource and what
happens if I assign something to it. So I created tables without names
and thought I would replace the old table by assigning it to the
datasource, but instead I added a nameless table to it. The solution
is simply give the table I create a unique name, so it really replaces
the old one with the same name.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top