Order gridview with linq data in asp - asp.net

I am using EF6 with Linq and i am trying to order data from my Oracle database with the FileID.
This is my code to populate the data.
protected void Page_Load(object sender, EventArgs e)
{
this.Form.Enctype = "multipart/form-data"; //this is required for multi uploading
if (!IsPostBack)
{
PopulateUploadedFiles();
}
}
private void PopulateUploadedFiles()
{
//Populate data
using(Mox_Database_Entities dc = new Mox_Database_Entities())
{
GridView1.DataSource = dc.FILE_UPLOADING.ToList();
GridView1.DataBind();
}
}
I want an ascending order for this gridview. Allowsorting = true in my gridview. I tried multiple ways to get this right but it still doesn't work.
Does anyone had this problem before?
thanks in advance for the effort.

Related

Update the data in database in asp.net

I can successfully select the data I want to update to another page and populate my text boxes but if I set the selected values to my textbox and then try to update it wouldn't work and the same data is shown in database table.
However if I DO NOT set those values to my textboxes, then I can successfully update which is not what I am after.
I would like the user to see the data and record that s being updated
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
UserClassesDataContext db= new UserClassesDataContext();
var qr = from user in db.Users
where user.user_id == new Guid(Request.QueryString["user_id"])
select user;
foreach (var q in qr)
{
TextBox1.Text = q.user_name;
TextBox2.Text = q.password;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
UserClassesDataContext db = new UserClassesDataContext();
var qr = from user in db.Users
where user.user_id == new Guid(Request.QueryString["user_id"])
select user;
foreach (var q in qr)
{
q.user_name = TextBox1.Text;
q.password = TextBox2.Text;
}
db.SubmitChanges();
Response.Redirect("Default.aspx");
}
What am I doing wrong?
Thanks
The problem is, when you submit the button, the code inside Page_Load event is executing again.That means it is reading the data from your table and setting the value to textboxes(thus overwriting what user updated via the form ) and you are updating your record with this values (original values). So basically you are updating the rows with same values.
You can use the Page.IsPostBack property to determine whether the event is occurred by a postback(button click) or initial page load.
This should fix it.
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
// to do: read and set to textbox here.
}
}

using selectcommand on code behind with gridview

I have a sqldatascource that I need to pass null values to it and then use the selectcommand specified by a stored procedure and then using the result query to populate a gridview on the page load
notes: I tried the stored procedure on sql server managment studio and its working fine
I alread specified sqldatascource on for gridview1 in the page design view
I tried this code but the gridview still shows empty
protected void Page_Load(object sender, EventArgs e)
{
SqlDataSource1.SelectParameters["location"].DefaultValue = null;
SqlDataSource1.SelectParameters["time"].DefaultValue = null;
SqlDataSource1.SelectParameters["date"].DefaultValue = null;
SqlDataSource1.DataBind();
GridView1.DataBind();
}
I think using null does not represent a database NULL.
This might work
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
SqlDataSource1.SelectParameters["location"].DefaultValue = System.DbNull.Value;
SqlDataSource1.SelectParameters["time"].DefaultValue = System.DbNull.Value;
SqlDataSource1.SelectParameters["date"].DefaultValue = System.DbNull.Value;
SqlDataSource1.DataBind();
GridView1.DataBind();
}
}

When to fill a sorted asp:GridView?

i've tried to ask this question a number of ways. It's a difficult question to answer because you have to understand what's going on.
When do i fill a GridView?
The nieve answer is during Page_Load, if not a PostBack:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet ds = GetStuffToShow();
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
The problem with that is that if it is a postback, the grid is not filled. The reason the grid is not filled is because we've turned off the viewstate of the grid.
So don't look at IsPostBack
We need to always fill the grid, postback or not:
protected void Page_Load(object sender, EventArgs e)
{
DataSet ds = GetStuffToShow();
GridView1.DataSource = ds;
GridView1.DataBind();
}
The problem with that is that if the user sorts a column, the OnSorting event is called after both Page_Init and Page_Load:
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataSet ds = GetStuffToShow(e.SortExpression, e.SortDirection);
GridView1.DataSource = ds;
GridView1.DataBind();
}
we've run two database queries, when only one was required.
Cache is fine for column sorting
If i'm willing to accept invalid cache during column sorting, i can store the DataSet in the session variable, as long as i invalidate it for any other operation.
The problem is the OnSorting event is called after i need it (Page_Load):
protected void Page_Load(object sender, EventArgs e)
{
if (AGridViewOnSortingEventIsntBeingRaised)
{
DataSet ds = GetStuffToShow();
StoreTheDatasetInTheSessionSomehowInCaseTheyCallSortInTheFuture(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataSet ds = GetDataSetOutOfSessionSomehowThatDamnWellBetterBeThere();
SomehowSortAReadOnlyDisconnectedDataSet(ds, e.SortExpression, e.SortDirection);
GridView1.DataSource = ds;
GridView1.DataBind();
}
Fear of the unknown
Then there's still the terror i have because i turned off viewstate of the GridView. i don't think that a read-only asp:GridView should need tens of kilobytes base64 encoded, when i can just rebuild it from the server (or from memory).
But i believe that i am obligated to return the GridView to the state it was in the last time the page was rendered. And i have to do it before Page_Load (i.e. during Page_Init). i have this fear because someone said so. So i turn it into
protected void Page_Init(object sender, EventArgs e)
{
if (AGridViewOnSortingEventIsntBeingRaised)
{
DataSet ds = GetStuffToShow();
StoreTheDatasetInTheSessionSomehowInCaseTheyCallSortInTheFuture(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
The problem with this is that GetStuffToShow depends on things the user has typed into text boxes, which don't exist during Page_Init
Anyway, i'm rambling. It's too hot in here. Hopefully this question will be answered, unlike my other recent frustrations with asp.net
Bonus Reading
Sorting GridView Formed With Data Set
By adding a couple of hidden fields, one for the sort expression, and the other for the sort direction you can use those values to populate the GridView once at page load and then update the sorting in the Sorting event (sort code modified from the All-In-One Code Framework GridView sample):
protected void Page_Load(object sender, EventArgs e)
{
DataSet ds = GetStuffToShow();
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
// If the sorting column is the same as the previous one,
// then change the sort order.
if (SortExpression.Value.Equals(e.SortExpression))
{
SortDirection.Value = SortDirection.Value.Equals("ASC") ? "DESC" : "ASC";
}
// If sorting column is another column,
// then specify the sort order to "Ascending".
else
{
SortExpression.Value = e.SortExpression;
SortDirection.Value = "ASC";
}
var sortedView = new DataView(<convert your DataSet to a DataTable>)
{ Sort = string.Format("{0} {1}", this.SortExpression.Value, this.SortDirection.Value) };
GridView1.DataSource = sortedView;
GridView1.DataBind();
}
Note that SortDirection and SortExpression are the hidden fields. This also lends itself well to caching the DataSet.
Also, I wouldn't be concerned about the Page_Init issue that you brought up. That should only apply if you are dynamically creating your Controls.
A simple solution is to call Gridview.DataBind() on the Page.Pre_Render event, which makes it called after having handled any Button/Sorting, events. This a good way to ensure you call it only once per Request.
To make things clearer, it is also a good thing to access your dataset through a Property which will basically call your "Store-The-Dataset-In-The-Session-Somehow-In-Case-They-Call-Sort-In-The-Future" method in its Set part and your "Get-Data-Set-Out-Of-Session-That-Had-Better-Be-There" in the Get part.
You may try to fill the grid on Gridview Needdatasource event
it will be called when ever you perform a postback and get the proper functionality what ever you code in the event.
also if you want to bind it again you can just data databind method and that will call the needdatasource event again

Fields not changing in Formview when moving Pagination

I have a formview that on page load makes a call to a sql server and retrieves 5 records which I want the formview to paginate though.
I have sucessfully connected to the db, filled a dataset, and returned data when the web page renders. The problem is that when I move to a new page, the data does not change in the databound field.
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
conn = new SqlConnection(connstr);
ds = new DataSet();
da = new SqlDataAdapter("call to stored proc", conn);
try
{
conn.Open();
da.Fill(ds, "m");
FormView1.DataSource = ds;
FormView1.DataKeyNames = new string[] { "PropKey" };
FormView1.DataBind();
}
catch (Exception ex)
{
Result = ex.Message;
}
finally
{
conn.Close();
}
}
Next when the paginate buttons are clicked I have this:
protected void FormView1_PageIndexChanging1(object sender, FormViewPageEventArgs e)
{
FormView1.PageIndex = e.NewPageIndex;
}
Please help,
Thanks
You will need to bind the data to the FormView just after setting the new page index like below.
protected void FormView1_PageIndexChanging1(object sender, FormViewPageEventArgs e)
{
FormView1.PageIndex = e.NewPageIndex;
BindFormViewData();
}
This is required because the FormView only displays the data for the active record and does not store any other records from the datasource, so upon change of the page index, the datasource is required to be bound again. See: Paging in a FormView Web Server Control
From the above link:
If the FormView control is bound to a data source control, or to any
data structure that implements the ICollection interface (including
datasets), the control gets all the records from the data source,
displays the record for the current page, and discards the rest. When
the user moves to another page, the FormView control repeats the
process, displaying a different record.
Hope this helps.

Read data from SqlDataSource or GridView

I have SqlDataSource and GridView on web form. GridView.DataSourceID = mySqlDataSource.
When I call myGridView.DataBind(), all data successfully bind on the page.
How is it possible to read already got data from mySqlDataSource or myGridView objects as DataTable or DataView? Thanks
The data in the gridview can read by using FindControl property of Gridview control. For example, for reading values set in the Checkbox column in the grid.
for (i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chk = (CheckBox)GridView1.Rows[i].FindControl("checkbox1");
//here code for using value captured in chk
}
Provided your data set isn't gigantic, you could store it in the Session, bind your GridView to the Session data, and then re-use the Session data in your other web objects.
Your code would then look something like this (you'll have to forgive any minor inaccuracies -- I'm away from my development box at the moment):
protected override OnInit(object sender, EventArgs e)
{
base.OnInit();
if (Page.IsPostback == false)
{
SetSessionData();
}
//
// Set your GridView, DataTable, DataView, etc. events here.
//
}
void SetSessionData();
{
List<YourDataBoundObject> myDataBoundObject = GetYourDataBoundObject(); // Or Collection<T>, IEnumerable<T>, etc.
Session["data"] = myDataBoundObject;
}
void YourGridView_Load(object sender, EventArgs e)
{
BindYourGridView();
}
void BindYourGridView()
{
YourGridView.DataSource = GetSessionData();
YourGridView.DataBind();
}
List<YourDataBoundObject> GetSessionData()
{
return (List<YourDataBoundObject>) Session["data"];
}
void YourDataTable_Load(object sender, EventArgs e)
{
BindYourDataTable();
}
void BindYourDataTable()
{
YourDataTable.DataSource = GetSessionData();
YourDataTable.DataBind();
}

Resources