i am using data table to bind data to gridview.I want to allow paging. How can I do paging?
This is my code I used.
SqlConnection con = new SqlConnection(getconnectionString());
SqlCommand cmd = new SqlCommand("Sps_pagingshow", con);
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
//cmd.Parameters.AddWithValue("#PageIndex", pageIndex);
//cmd.Parameters.AddWithValue("#PageSize", int.Parse(ddlPageSize.SelectedValue));
//cmd.Parameters.Add("#RecordCount", SqlDbType.Int, 4);
//cmd.Parameters["#RecordCount"].Direction = ParameterDirection.Output;
IDataReader idr = cmd.ExecuteReader();
GridView1.DataSource = idr;
GridView1.DataBind();
idr.Close();
con.Close();
Datatable is disconnected architecture, So it wont support the pagination.
According to msdn, automatic paging via the GridView is only supported for data sources, or for objects that implement the ICollection interface or one of its descendants (i.e. Enumerable, Dictionary, List, Queue, Stack, etc.)
A DataTable doesn't qualify on either of those counts, so your suspecion that the DataTable does not support automatic paging is correct. However, as you have learned, you can page through a DataTable programmatically. Another approach is to use the DataTable to populate a collection which supports paging.
Use "OnPageIndexChanging" event of GridView to allow default paging as.
protected void index_changing(object sender, GridViewPageEventArgs e)
{
gridview.PageIndex = e.NewPageIndex;
}
Thanks.
Related
I am using MVC3 and getting country table from database and storing in cache. First time it get the data from caching but when I refresh the page its give me only datatable schema only. It give me only fields countryid,countryname, countrycode. But it dont give me data.
DataTable dt_Country = (DataTable)HttpContext.Current.Cache["Countries"];
if (dt_Country == null)
{
DataTable dt_State1 = new DataTable();
SqlConnection con = new SqlConnection(Common.ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("ConstantsCountriesSelectAll", con);
SqlDataAdapter ada = new SqlDataAdapter(cmd);
ada.Fill(dt_State1);
HttpContext.Current.Cache["Countries"] = dt_State1;
dt_Country = (DataTable)HttpContext.Current.Cache["Countries"];
}
//dt_Country = (DataTable)HttpContext.Current.Cache["Countries"];
return dt_Country;
I am trying to insert DataTable into a DB table (the DB is on a mobile device - Psion), using a DataAdapter. from some reason, it does not work - when i check the DB table - it simply appears as an empty table...
the code:
>
private void btnCommTables_Click(object sender, EventArgs e)
{
try
{
DataSet ds = WSDanielGroup.Instance._WSDanielGroupToDevice.GetLoadTables();
DataTable DT = ds.Tables["Peer"];
string SelectCMD = "INSERT INTO Peer(ID,PeerID) Values(?,?)";
SqlCeConnection cn = new SqlCeConnection(DBManager.sLocalConnectionString);
SqlCeDataAdapter da=new SqlCeDataAdapter();
da.InsertCommand = new SqlCeCommand(SelectCMD, cn);
cn.Open();
da.InsertCommand.Parameters.Add("#ID", SqlDbType.Int,4,"ID");
da.InsertCommand.Parameters.Add("#PeerID", SqlDbType.NVarChar,50, "PeerID");
int numRows = da.Update(DT);
}
One possible explanation is that your DataTable doesn't have the correct RowVersions. The DataAdapter will only update rows that have been changed in the table. If you get it from somewhere else, it thinks everything's OK and nothing needs to be updated (rows not marked "dirty"). More info here.
I want to do custom sorting on a ListView which has a DataTable as ItemsSource:
myListView.ItemsSource = (data as DataTable);
And this are the first lines of my sorting function:
DataView view = (myListView.ItemsSource as DataTable).DefaultView;
ListCollectionView coll = (ListCollectionView)CollectionViewSource.GetDefaultView(view);
The second line throws an execption like:
Unable to cast "System.Windows.Data.BindingListCollectionView" to "System.Windows.Data.ListCollectionView"
Has anyone a solution? Thx 4 answers
It returns an ICollectionView that is not a ListCollectionView. You most likely want a view on top of a view to get the features that ListCollectionView has. And since ICollectionView implements CollectionChanged, you wouldn't want to use BindingListCollectionView.
DataView view = (myListView.ItemsSource as DataTable).DefaultView;
ListCollectionView coll = new ListCollectionView(CollectionViewSource.GetDefaultView(view));
Although an alternative would be:
DataView view = (myListView.ItemsSource as DataTable).DefaultView;
BindingListCollectionView coll = new BindingListCollectionView(view);
If you only wanted only one view.
If you are binding directly to a WPF control, it is best to bind directly to it without making a BindingListCollectionView/ListCollectionView, as DefaultView already allows sorting of the DataTable.
Binding binding = new Binding() { Source = (myListView.ItemsSource as DataTable) };
this.myListView.SetBinding(myListView.ItemsSourceProperty, binding);
DataView view = (myListView.ItemsSource as DataTable).DefaultView;
view.Sort = "Age";
Hopefully Helpful,
TamusJRoyce
OK, I am amittedly new to LINQ and have spent the last week reading everything I could on it. I am just playing around, trying to follow some examples I have found (a PDF from Scott Gu on the topic, in fact) and I am at a complete loss. Can someone please tell me why, when I bind a GridView to the query below, using the code below, I get no data?? I can see the results while debugging, so I know they are coming back from the DB, they are just not apparently binding correctly. I read something saying you could not bind directly to the result,and that you have to use a BindingSource as an intermediate step?
Someone, please tell me what I am missing here.
protected void Page_Load(object sender, EventArgs e)
{
SwapDBDataContext db = new SwapDBDataContext();
var users = from u in db.aspnet_Users
select new
{
Name = u.UserName,
ID = u.UserId
};
GridView1.DataSource = users;
GridView1.DataBind();
}
I am just using an empty GridView. I had assumed that the binding would take care of setting up the columns to match the resulting columns from the query - was that a stupid beginners mistake?
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
You should not have to convert to a List or Array. Binding requires, at a minimum, an IEnumerable<T>, which is what your Users variable is. Anonymous types are simply pre-compile place holders for compiler generated concrete types, so you should also be able to bind to anonymous types.
Your GridView may not have the AutoGeneratedColumns property set, which is what is required to have the data source define what columns appear. Try enabling that, and see if your GridView displays your queries results.
Cant understand why this shouldn't work. I whipped together a page using (almost) your code. It works perfectly for me.
protected void Page_Load(object sender, EventArgs e)
{
BlodsockerkollenDataContext db = new BlodsockerkollenDataContext();
var members = from m in db.Members
select new { Id = m.Id, Email = m.Email };
GridView1.DataSource = members;
GridView1.DataBind();
}
I don't agree with the suggested answers stating you should use ToList(). The GridView is capable of taking and traversing an IEnumerable, and IQueryable inherits IEnumerable.
And no, there should be no need to declare a BindingSource.
Maybe you have declared something in your GridView? Mine is just empty, pulled straight in from the toolbox:
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
SwapDBDataContext db = new SwapDBDataContext();
GridView1.DataSource = from u in db.aspnet_Users
select new
{
Name = u.UserName,
ID = u.UserId
};
GridView1.DataBind();
}
Try doing
GridView1.DataSource = users.ToList();
or
GridView1.DataSource = users.ToArray();
Is possibly that the query isn't executing at all, because of deferred execution.
I have a Linq query that I copy to a DataTable which is then used to populate a gridview. I am using a group by "key" and "count" which I evaluate in the aspx page for a master/detail gridview with a repeater.
The problem that I am encountering is that the gridview datasource and bind to the datatable is not presenting me with any additional pages that are part of the data.
My query is:
// Using Linq generate the query command from the DataTable
var query = from c in dtDataTable_GridView.AsEnumerable()
group c by c.Field<string>("CLIN") into g
select new
{
Key = g.Key,
Count = g.Count(),
Items = from i in g
select new
{
CLIN = i.Field<string>("CLIN"),
SLIN = i.Field<string>("SLIN"),
ACRN = i.Field<string>("ACRN"),
CLINType = i.Field<string>("CLINType"),
Option = i.Field<string>("Option"),
Unit = i.Field<string>("Unit")
}
};
// Use extension methods to create new DataTable from query
dtTaskOrderTable = query.CopyToDataTable();
// Set the datasource
gridview1.DataSource = dtTaskOrderTable;
// Bind to the GridView
gridview1.DataBind();
If I use the original datatable (dtDataTable_GridView) directly I have paging but once I do the Linq Query and copy it back to a new datatable (dtTaskOrderTable) I lose the paging feature.
Also how do I get a value from a column name ("Option" for instance) if it is part of "Items"?
Any help would be appreciated.
Thanks,
ChrisB
Please disregard the previous answer I will delete it
It requires ICollection interface for paging.
Neither IEnumerable nore IQuerable will not work
List<(Of <(T>)>) will work as Lists implement Icollection interface
So you need
gridview1.DataSource = dtTaskOrderTable.ToList();