C# Reusing an Adapter to populate other controls - c#

I'm using the following code to populate a DataGridView (sqliteAdapter derives from DbDataAdapter):
sqliteAdapter.SelectCommand.CommandText = SQLCommand;
sqliteConn.Open();
using (DataTable dt = new DataTable())
{
sqLiteAdapter.Fill(dt);
dataGridRes.DataSource = dt;
}
The Actual SQLCommand is:
SELECT Email NOTNULL AS Sel, Regiao, Distrito, Grupo, MG, ID, Nome, Morada, Email
FROM assessores
Now, I would like to reuse this DataTable to populate other controls in the form. Namely 4 CheckedListBox controls. I was hoping to avoid any further connections to the database by "filtering" the current DataTable to something like (Invalid code. Illustrative only)
SELECT Distinct Regiao FROM DataTable
SELECT Distinct Distrito FROM DataTable
SELECT Distinct Grupo FROM DataTable
SELECT Distinct MG FROM DataTable
My forays into adapter and DataTable properties and methods have been fruitless.

Controls can be bound to any collection, not just a DataTable.
You can therefore use LINQ, like this:
myControl.DataSource = dt.AsEnumerable().Select(dr => dr.Field<string>("Regiao")).Distinct().ToArray();

You can filter a DataTable but it returns an array of DataRow objects rather than a filtered DataTable, which can't be directly bound to a DataGrid or other data bound control. Instead use a DataView:
DataView dv = new DataView(dt);
dv.RowFilter = "Filter Expresion";
dg.DataSource = dv;
See Sorting and Filtering Data Using a DataView

Related

DataTable Sorting without creating new DataTable with maintaining RowState

I am using DataTable. In which I want to sort on particular columns without creating copy. I have also tried with DataTable.Select() but it required new table for sorted output which will be not worked for me as my source datatable is bound with control.
You can take any example of DataTable
So how can I achieve the task?
Below code will help you to achieve your requirement
IEnumerable<DataRow> data = from dt in dtTemp.AsEnumerable()
orderby dt.Field<Int32>("IDColumn"), dt.Field<String>("NameColumn") ascending
select dt;
Below code as an example:
DataTable dt = new DataTable();
//Populate dt here
dt.DefaultView.Sort = string.Format("{0} {1}", "column name here", "ASC"); //sort ascending
dt = dt.DefaultView.ToTable();

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;

Dataset Sorting using C# on a column with Datetime datatype

I am having a dataset (Dataset ds) and below you can find the field with demo data inside the dataset.
In my Dataset , their is column with name Date (Datatype- DateTime) and i want to sort this column.I cant do the sorting from SQl because the Dataset is a merge of 2 Different Dataset.
Please help me that how i do the sorting in dataset.
Date Volume
07/19/201211:30AM 12
07/18/201201:30PM 13
07/17/201203:30PM 22
This is a simple Linq-To-DataSet approach:
IEnumerable<DataRow> orderedRows = dataSet.Tables[0].AsEnumerable()
.OrderBy(r => r.Field<DateTime>("Date"));
Now you can use that as DataSource or enumerate it in a foreach. If you need to materialize it, you might want to create a new DataTable from it:
DataTable tblOrdered = orderedRows.CopyToDataTable();
You can create a data view from your data-set.
Then you can use the DataView.Sort Property to sort your data.
eg.
DataView myDataView = DT.DefaultView;
myDataView.Sort = "Date DESC";
Read more about Introduction to Filtering and Sorting in Datasets
Using Dataview you can sort your Datatable.
Just put your Datatable in Dataview
Look at the following example :
You have dtlog table which having two columns one is date and another one is detials.
you want to sort your datatable by date column.
DataTable dtlog = new DataTable();
dtlog.Columns.Add("date");
dtlog.Columns.Add("details");
1.create dataview and put your datatable in view
DataView dtview = new DataView(dtlog);
string sortstring = "date DESC"; // sorting in descending manner
dtview.Sort = sortstring;
2.Create another table where you can save your sorted dataview
DataTable dtsort =dtview.ToTable();
You can do this by a DataView. If your column which is holding datetime is a datetime column
DataView dv = DataTable.DefaultView;
dv.Sort = "DateTime-ColumnName ASC";
It will not work on string column holding datetime as string.
The DataView of a DataTable have a sort property please pass the column name to it
E.g.
dataSet1.Table[0].DefautlView.Sort = "ColumnName";
default sort is by ascending order
For more see link http://msdn.microsoft.com/en-us/library/system.data.dataview.sort(v=vs.100).aspx
I find my solucion is add more columns to Datatable where we can save each part of a DateTime:
Tabla.Columns.Add("year", typeof(DateTime));
Tabla.Columns.Add("month", typeof(DateTime));
Tabla.Columns.Add("day", typeof(DateTime));
then we can sort our datatable with a DataView:
DataView myDataView = DT.DefaultView;
case 1: ASC
myDataView.Sort = "year asc, month asc, day asc";
case 2: DESC
myDataView.Sort = "year desc, month desc, day desc";
Tabla = myDataViwe.toTable();
result is our datatable sorted for a dateTime
It worked for Me:
dataTableEmpSurvey.DefaultView.Sort = "SNO";
var dataTableSorted = dataTableEmpSurvey.DefaultView.ToTable();
https://www.codeproject.com/Questions/219205/How-To-Sort-Datatable-in-csharp-net

sorting a data-table before adding into dataset

I have a dataset that i need to add into a dataset. I need to sort datatable before adding it into dataset.I can use DataView to sort the datatable but cannot figure out how to add this dataview into the dataset. Any ideas
DataView myDataView = MyDataTable.DefaultView;
myDataView.Sort = " Key1, Key2"
MyDataSet.Tables.Add(myDataView); // no overload that takes a dataview
You can create a DataTable by calling DataView.ToTable.

How to get the datasource of a gridview

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"];

Categories