Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How clear GridView in asp.net?

I doing a web page in asp.net and in a module have select a Excel archive with FileUpLoad 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 GridView 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;

ConnExcel.Open();
CmdExcel.CommandText = "SELECT * From ["Page1$"]";
Oda.SelectCommand = CmdExcel;
Oda.Fill(Dt);
ConnExcel.Close();

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

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

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

The error than show me is in the grdResultados.DataBind(); when called the second time.

like image 854
Fernando Zaiza Avatar asked Jun 05 '14 22:06

Fernando Zaiza


1 Answers

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

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

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; )
{
    grdResultados.Columns.RemoveAt(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

like image 105
Fernando Zaiza Avatar answered Oct 26 '22 23:10

Fernando Zaiza