How to get the datasource of a gridview - c#

I am using a gridview with sqldatasource. How to get back the datasource in the codebehind as a datatable?

Use System.Data.DataTable dt = (System.Data.DataTable)gview.DataSource; if you are binding a DataTable.
You can even extract the DataTable out of DataSet if you are binding DataSet as
System.Data.DataTable dt2 = (System.Data.DataTable)((System.Data.DataSet)gvValidDA.DataSource).Tables[0]; you will have to check the index of your table or table name as you prefer.
Happy coding.

Edited
Use SqlDataSource.Select Method and assign it to a dataview
DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
Then extract the datatable using
DataTable dt = (DataTable)dv.ToTable();

The actual data is not stored in the Gridview properties as the above answers pertain.
Using direct casting to the Gridview.DataSource is not enough, as it's actually NULL when the gridview has rendered!
You have to either reload the data directly from the SQL datasource...
DataSourceSelectArguments dss = new DataSourceSelectArguments();
DataView dvS = sdsADDorREMstudentData.Select(dss) as DataView;
DataTable dtS = dvS.ToTable() as DataTable;
if (dtS != null)
{
... etc...
}
Or you can use the ViewState to retain the data before the Gridview has rendered.
DataView dvClasses = (DataView)sdsClasses.Select(DataSourceSelectArguments.Empty);
gvStudents.DataSourceID = "sdsClasses";
gvStudents.DataSource = null; // Null out the source, as we have a SourceID instead
gvStudents.DataBind();
//save the data in a viewstate for later use (to control adding and removing students, without doing a postback! See ADD & REM methods below)
DataView dv = (DataView)dvClasses;
DataTable dt = new DataTable();
if (dv != null)
{
dt = dv.ToTable();
ViewState["gv"] = dt;
}
And use the ViewState to turn it back into a DataTable, when you need to use the data AFTER the Gridview has rendered...
DataTable dt = (DataTable)ViewState["gv"];

Related

Datagridview Column sort in descending order

I want to sort my datagrid view column which is non data bound. so please help me . following is the code
private void dgvDailyEntry_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
this.dgvDailyEntry.Rows[e.RowIndex].Cells["sno"].Value = (e.RowIndex + 1).ToString();
}
sort
Thanks in Advance
If it's not bound, I'd assume you have a datatable assigned as datasource. If you can sort the data while obtaining the datatable, the best is to sort it right there. If you can't (i.e. data are generated in random order), sort the datatable then.
C#
Datatable dt; // that is the source datatable
DataView SortedDataView = new DataView();
SortedDataView = dt.DefaultView;
SortedDataView.Sort = "COlumnNameToSortBy DESC";
dt = SortedDataView.ToTable();
VB.NET:
Dim dt as Datatable ' that is the source datatable
Dim SortedDataView As New DataView
SortedDataView = dt.DefaultView
SortedDataView.Sort = "COlumnNameToSortBy DESC"
dt = SortedDataView.ToTable()
If you somehow don't have datatable, I'd certainly recommend to implement it. It's a good practice even if you don't need sorting and such.

update datatable inside a dataset

I want to know how to update a Datatable which is inside a dataset.I have a datatable in which i have details of some item.Now i want to add this into a dataset for some purpose and update it.Give me some suggesions to solve this..
this is my code:
DataRow dr;
dr = Basket_DataTable.NewRow();
Basket_DataTable.Rows.Add(dr);
dr["PId"] = getPId.ToString();
dr["ProductName"] = getProductName.ToString();
dr["ImagePath"] = getImagePath.ToString();
dr["ProductPrice"] = getProductPrice.ToString();
dr["Quantity"] = getQuantity.ToString();
dr["ProductDescription"] = getProductDescription.ToString();
dr["TotalPrice"] = getProductPrice.ToString();
Basket_DataTable.AcceptChanges();
Basket_DataTable is my datatable which i need to add to a dataset and update..
I believe you want to add new Rows to your existing DataTable in your DataSet. Instead of creating a new DataTable, your Basket_DataTable should refer to your data table in the data set.
Something like.
//Create new Row from your DataTable in DataSet
DataRow dr = yourDataSet.Tables["Basket_DataTable"].NewRow();
// here you can refer to your datatable with the index as well
//e.g. yourDataSet.Tables[0]
Basket_DataTable.Rows.Add(dr);
dr["PId"] = getPId.ToString();
dr["ProductName"] = getProductName.ToString();
dr["ImagePath"] = getImagePath.ToString();
dr["ProductPrice"] = getProductPrice.ToString();
dr["Quantity"] = getQuantity.ToString();
dr["ProductDescription"] = getProductDescription.ToString();
dr["TotalPrice"] = getProductPrice.ToString();
//Remember to add your row to the table.
yourDataSet.Tables["Basket_DataTable"].Rows.Add(dr);
In your current code you are not adding the new row to the datatable. Remember to include the row in the datatable.
If the DataTable is already in an existing DataSet, but you want to add it to another one, you need to create a copy first - A DataTable instance can only have one parent DataSet.
DataTable Basket_DataTable_copy = Basket_DataTable.Copy();
yourDataSet.Tables.Add(Basket_DataTable_copy);
Then you can do your updates on Basket_DataTable_copy
see DataTable.Copy on MSDN

gridView.DataSource as DataTable is setting a null in asp.net

I am setting my gridview.datasource into a datatable variable as below:
DataTable dt = gvPaymentHistory.DataSource as DataTable;
The gvPaymentHistory.DataSource has a record, however, the dt is null after that line has executed. How can I pass the Datasource records to dt?
EDIT
DataSource is List collection of a class object. It's not a DataSet
Simple way is to store the data source of the grid in view source when u r binding the data to the grid and then retrieve it from the view source every time you need it.
Gridview.Datasource = yourdatasource;
ViewState["mydatasource"] = yourdatasource;
While retrieving
DataTable dt = ViewState["mydatasource"] as DataTable;
Hope this solves your problem.
Try This Way: Use BindingSource
BindingSource bs = (BindingSource)gvPaymentHistory.DataSource;
DataTable dt =((YourDataSetType) (bs.DataSource)).Tables[0];
EDIT
if the bidning type is list than try out
List<CodeEntity> data= gvPaymentHistory.DataSource as List<CodeEntity>;
or
List<CodeEntity> codes = (List<CodeEntity>)gvPaymentHistory.DataSource;
check this
if(gvPaymentHistory.DataSource is DataTable)
DataTable dt = gvPaymentHistory.DataSource as DataTable;
if(gvPaymentHistory.DataSource is DataView )
DataView dv = gvPaymentHistory.DataSource as DataView;

How do I swap TableAdapter DataViews?

I want a user to have different "views" of a TableAdapter. These do not need to be committed back to the database.
I have tried something like the following
mytba.DataView = someOtherDataView;
with no success.
Is it possible to do this?
You need to create a new DataView from the underlying DataTable.
It's been a while since I used TableAdapters, but you can fill a data table with it
DataTable dt = new DataTable();
MyTableAdapter.Fill(dt);
DataView dv1 = new DataView(dt);
DataView dv2 = new DataView(dt);

How to sort data in GridView in asp.net

How to sort datatable obtained by GridView according to some column.
I am trying to do something like this but it is not working.
protected void GridView_Sorting(object sender, GridViewSortEventArgs e)
{
if (sender.GetType() != typeof(GridView))
return;
DataTable dt = (DataTable)((GridView)sender).DataSource;
DataTable dtClone = dt.Clone();
dt.AsEnumerable().OrderBy(row => row.Field <string>(e.SortExpression));
((GridView)sender).Source(dtClone);
}
You can either re-bind the gridview to the sorted datatable, or you can apply the sort expression to the gridview itself rather than the underlying bound table.
This is a pretty good summary with links to examples:
http://msdn.microsoft.com/en-us/library/hwf94875.aspx
Add the attributes OnSorting="gridView_Sorting" AllowSorting="true" in Gridview
and SortExpression="ColumnName" in the column
and implement OnSorting Event.
check the links
Sorting the GridView's Data
How to sort the data in grid view?
How to sort data into GridView
Sorting Data in a GridView
How to sort GridView?
I've done something like this in the past to sort a DataTable:
DataTable dt = new DataTable(); // your data table
dt.DefaultView.Sort = "your_field" + "sort_direction";
DataView dv = new DataView(dt);
dv.Sort = ("your_field" + "sort_direction");
yourGridView.DataSource = dv;
When sorting, make sure to cast your table to a DataView. You'll save yourself a lot of time over manually implementing sorting methods.

Categories