How clear GridView in asp.net? - c#

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.

Just use null value:
grdResultados.DataSource = null;
grdResultados.DataBind();

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

try this
grdResultados.DataSource = null;
or
grdResultados.Rows.Clear();
then rebind the gridview

int gvHasRows = grdResultados.Rows.Count;
if (gvHasRows > 0)
{
grdResultados.Columns.Clear();
grdResultados.DataBind();
}
First check that there is data in the Gridview before trying to clear.
Rows has no Clear function.

If you use a Session clear the session Example:
DataTable ds = new DataTable();
ds = null;
GV.DataSource = ds;
GV.DataBind();
for (int i = 0; GV.Columns.Count > i; )
{
GV.Columns.RemoveAt(i);
}
ViewState["CurrentData"] = null;

Make an empty data table with just your column names and re bind

You can simply do this:
GridView1.SelectedIndex = -1;

If dataset IsNot Nothing AndAlso dataset.Tables.Count > 0 AndAlso dataset.Tables(0).Rows.Count > 0 Then
grid.DataSource = dataset
grid.DataBind()
Else
grid.DataSource = Nothing
grid.DataBind()

If you're using a XAML defined Grid, use this instead:
GridView1.Children.Clear();
GridView1.RowDefinitions.Clear();
GridView1.ColumnDefinitions.Clear();

Related

DataGridView add column by code

I need to add columns to my DataGridView dynamically... to do this here is my code:
dgv.Columns.Clear();
dgv.AutoGenerateColumns = false;
for (int i = 0; i < fields.Length; i++)
{
var newColumn = new DataGridViewColumn(new DataGridViewTextBoxCell());
newColumn.Name = fields[i];
newColumn.DataPropertyName = fields[i];
newColumn.HeaderText = fields[i];
dgv.Columns.Add(newColumn);
}
And after, when I link my query to the DataSource I retrieve this error:
The value can't be null.
Parameter name: columnName
And the strange thing is that here is my DataGridView/DataTable situation:
The names seems right...
The other strange thing is that the first row is shown, but the others gives the exception (the query is OK and the data are valid...)
here is the code to create the DataSource for the table:
public DataTable getData()
{
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand(item.Query, db.getConnection());
SqlDataAdapter dap = new SqlDataAdapter();
dap.SelectCommand = cmd;
dap.Fill(ds);
return ds.Tables[0];
}
and after:
dgv.DataSource = getData();

C# DataSet.Tables[0].GetChanges(); always returns all rows

I have bind DataGridView in C# WinForms from text file as shown below
onPageLoad
DataTable table = new DataTable();
table.Columns.Add(Column0);
table.Columns.Add(Column1);
table.Columns.Add(Column2);
table.Columns.Add(Column3);
using (StreamReader sr = new StreamReader(Environment.CurrentDirectory + #"/data.txt"))
{
while (!sr.EndOfStream)
{
string[] parts = sr.ReadLine().Split(',');
DeviceIDCounter = DeviceIDCounter + 1;
table.Rows.Add(DeviceIDCounter, parts[0], parts[1], parts[2]);
}
}
dataSet = new DataSet();
dataSet.Clear();
dataSet.Tables.Add(table);
dataGridView1.DataSource = dataSet.Tables[0];
dataGridView1.AllowUserToAddRows = false;
dataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView1.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView1.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
DeviceIDCounter = 0;
Now on updating single row in the dataGridView1, it always return all rows
onButtonClick after updating row
DataTable dtRecordsUpdated = dataSet.Tables[0].GetChanges(); //always returning total rows
if (dtRecordsUpdated != null && dtRecordsUpdated.Rows.Count > 0)
{
Cursor.Current = Cursors.WaitCursor;
Cursor.Current = Cursors.Default;
}
else
{}
On the other hand, my other function which is bind DataGridView from SQLServer is working as expected.
Thanks
You need to update to DataSource of DGV after you made some changes like this:
((System.Data.DataTable)this.dataGridView1.DataSource).AcceptChanges();
DataTable.GetChanges Method: Gets a copy of the DataTable that contains all changes made to it since it was loaded or AcceptChanges was last called.
If you need to catch what has changed you need to AcceptChanges
You get all the rows because the dataTable considers that all the rows have New.State since you never acceptChanges
PS : there is no need to create the DataSet if you are just passing the DataTable to the DataGridView

Delete selected row

I want to delete a row from my data set,update the content of the listbox and update the content of the database.I have the following piece of code but it seems like nothing happens,all the rows are still there.
What am I not doing?
DataSet ds = new DataSet();
SqlDataAdapter daf = new SqlDataAdapter();
ds.Tables["Film"].Constraints.Add("PK_Film", ds.Tables["Film"].Columns["id"], true);
int ind = listBoxchildren.SelectedIndex;
listBoxchildren.DataSource = null;
ds.Tables["Film"].Rows[ind].Delete();
ds.Tables["Film"].AcceptChanges();
daf.Update(ds,"Film");
listBoxchildren.DataSource = ds;
listBoxchildren.DisplayMember = "Director.fk_FilmDir.title";
Unbound the data source before deleting the item,
int selectedIndex = listBoxchildren.SelectedIndex;
listBoxchildren.DataSource = null;
ds.Tables["Film"].Rows[selectedIndex].Delete();
ds.Tables["Film"].AcceptChanges();
daf.Update(ds,"Film");
listBoxchildren.DataSource = ds;

How to bind Dataset to DataGridView in windows application

I have created Windows Application. In this, I have multiple tables in dataset, now I want to bind that to a single DataGridView. Can anybody help me?
following will show one table of dataset
DataGridView1.AutoGenerateColumns = true;
DataGridView1.DataSource = ds; // dataset
DataGridView1.DataMember = "TableName"; // table name you need to show
if you want to show multiple tables, you need to create one datatable or custom object collection out of all tables.
if two tables with same table schema
dtAll = dtOne.Copy(); // dtOne = ds.Tables[0]
dtAll.Merge(dtTwo); // dtTwo = dtOne = ds.Tables[1]
DataGridView1.AutoGenerateColumns = true;
DataGridView1.DataSource = dtAll ; // datatable
sample code to mode all tables
DataTable dtAll = ds.Tables[0].Copy();
for (var i = 1; i < ds.Tables.Count; i++)
{
dtAll.Merge(ds.Tables[i]);
}
DataGridView1.AutoGenerateColumns = true;
DataGridView1.DataSource = dtAll ;
use like this :-
gridview1.DataSource = ds.Tables[0]; <-- Use index or your table name which you want to bind
gridview1.DataBind();
I hope it helps!!
you can set the dataset to grid as follows:
//assuming your dataset object is ds
datagridview1.datasource= ds;
datagridview1.datamember= tablename.ToString();
tablename is the name of the table, which you want to show on the grid.
I hope, it helps.
B.R.
This Worked for me in asp.net
dgHistory.DataSource = ds.Tables[0]; // dgHistory is the datagrid
dgHistory.DataBind();

row count on dataset different than row count on datagridview

I'm pretty certain this is a problem with my data binding, but I'm not for sure what the problem is exactly. Using mysql I'm getting rows showing up in my dataset, but no rows showing up in my datagridview after I do the binding.
conn = new MySqlConnection("server=localhost;database=mydb;uid=user;password=pass");
conn.Open();
grid = new DataGridView();
grid.Dock = DockStyle.Fill;
ds = new DataSet();
adpt = new MySqlDataAdapter("select * from test limit 6;", conn);
adpt.Fill(ds);
Debug.WriteLine("data set rows found " + ds.Tables[0].Rows.Count);
binding = new BindingSource();
binding.DataSource = ds;
grid.DataSource = binding;
Debug.WriteLine("data grid rows found " + grid.Rows.Count);
conn.Close();
Controls.Add(grid);
The debug printout for this is 6 and 0. Does anybody know where my problem is?
Thanks in advance!
just do
grid.DataSource = ds.Tables[0];
Or.. If you want to using the BindingSource (say for filtering), set
binding.DataSource = ds.Tables[0];

Categories