Fernando Zaiza Fernando Zaiza - 11 months ago 87
ASP.NET (C#) Question

How clear GridView in asp.net?

I doing a web page in asp.net and in a module have select a Excel archive with

and click in a button import. Hitherto I'm fine. But in the moment than I want select other Excel archive and click in the button import, don't clear the
and show error. I attempt with this because I see in other questions similar to this.

With this I load the Grid

Conn = string.Format(Conn, DireccionArchivo, MostrarHDR);
OleDbConnection ConnExcel = new OleDbConnection(Conn);
OleDbCommand CmdExcel = new OleDbCommand();
OleDbDataAdapter Oda = new OleDbDataAdapter();
DataTable Dt = new DataTable();
CmdExcel.Connection = ConnExcel;

CmdExcel.CommandText = "SELECT * From ["Page1$"]";
Oda.SelectCommand = CmdExcel;

grdResultados.Caption = Path.GetFileName(DireccionArchivo);
grdResultados.DataSource = Dt;

And with this I want to clear the
and last y called of new the method of load the

DataTable ds = new DataTable();
ds = null;
grdResultados.DataSource = ds;

The error than show me is in the
when called the second time.

Answer Source

I resolved the problem, in the moment than clear the GridView with

DataTable ds = new DataTable();
ds = null;
grdResultados.DataSource = ds;

this clear the GridView but dont clear the names of columns, and this was the error, also have to clean the names of the columns. To remove the columns:

for (int i = 0; grdResultados.Columns.Count > i; )

and in the method of load th GridView must be generate the columns automatically with this property:

grdResultados.AutoGenerateColumns = true;

I leave this in case anyone else has the same problem