Call add variable to GridView in UpdatePanel cause recreate page every time - asp.net

I have that code in my page :
public partial class Utworz : System.Web.UI.Page
{
private List<Codes> Codes;
protected void Page_Load(object sender, EventArgs e)
{
this.GridView1.DataSource = Codes;
Codes = new List<Codes>();
}
protected void btn_AddKodManually_Click(object sender, EventArgs e)
{
Codes.Add(new Codes(code: this.TextBox1.Text, codeType: this.DropDownList1.SelectedValue));
this.GridView1.DataBind();
}
}
My page contains UpdatePanel in which I have form. I type data in this form and add to GridView.
and problem is that every time when I call Click method my Page was create new, and my variable Code also. Why this variable not save his state ?

Problem #1: The Codes variable is getting set to a new object every time the page loads. It will never have more than one code.
Problem #2: There is nothing here to hold the value of the Codes list from page view to page view. You need to store it somehow and retrieve it every time you want to rebind. For example, create a property called Codes and store the value in the viewstate. After adding a new code, rebind the grid.
I understand that you might expect the grid to hold it's state, but you're rebinding with a new object every time. Someone else might chime in here, but you may be able to restore the Codes object by calling:
Codes = this.GridView1.Datasource

Related

what is the lifespan of a datatable after an ajax call?

I'm doing a jquery ajax call to my server side c#. The c# code fills a datatable then sends the data to the aspx page using a JavaScriptSerializer:
The datatable is initialized as a public:
public partial class _Default : System.Web.UI.Page
{
DataTable myDataTable = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//SqlDataReader builds loads data into dataTable...
HttpContext.Current.Response.Write(serializer(dataTable));
}
The aspx page finally creates a table from the data by posting it back to the aspx page.
My next task is to sort the rows ascending/descending when the table heading is clicked (using another ajax call).
I'd like to perform a sort operation similar to the accepted answer in this question:
Sorting rows in a data table
Will the datatable from the initial ajax call still be in memory?
Thank you.
No, the dataTable will not be in memoty anymore. Every time you create a request a new instance of _Default will be created. After the request has been handled, it will be destroyed.
If you want the DataTable to remain in memory, you should save it in the Cache or the Application object (HttpContext.Current.Cache / HttpContext.Current.Application).

Sorting a gridview using a datatable, and datasource that is an ArrayList

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.sorting.aspx
This article deals with creating a datatable first, then creating a gridview from it, to aid in sorting. My predicament is slightly different.
I have a Gridview, that on Page_Load, I set the datasource to an ArrayList, and bind.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.GridView1.DataSource = RequestManager.Instance.GetAllRequests();
this.GridView1.DataBind();
}
}
Now I would like to sort this GridView, so on the aspx page, I set AllowSorting="true", and OnSorting="GridView1_Sorting". So far, so good. I have the SortExpressions set in the BoundFields, and when I click on it, I know the _Sorting event is triggered.
Now, since this is a postback operation, I cannot simply cast the datasource of the gridview to a DataTable to sort. Saving to ViewState is an option, but I cannot figure out how to do it.
I would like to use the simple solution on this page, except for the DataTable not being available to me. Thanks for looking.
If you're able to target .NET v3.5, I recommend using Linq. In your _Sorting event handler, get the array list you did in the Page_Load and rebind it.
For example, if the type contained in the array list are MyType instances that have properties named Default and SomeField:
protected void Grid_Sorting(object sender, GridViewSortEventArgs e)
{
Func<MyType, object> keySelector;
if(e.SortExpresion == "SomeField")
{
keySelector = dataItem => dataItem.SomeField;
}
else
{
keySelector = dataItem => dataItem.Default;
}
ArrayList dataItems = RequestManager.Instance.GetAllRequests();
this.GridView1.DataSource = dataItems.OfType<MyType>().OrderBy(keySelector);
this.GridView1.DataBind();
}
That will get you started, then later inspect the sort expression to see if it ends with ASC or DESC and conditionally call .OrderByDescending(keySelector).
Finally, I don't recommend stashing the list in ViewState, as the ObjectStateFormatter is only optimized for a handful of types. http://msdn.microsoft.com/en-us/library/system.web.ui.objectstateformatter.aspx
Maybe consider ASP.NET cache instead.

Where to store the datasets? - Session or Cache in ASP.NET

freshly boarded the asp.net boat.
I have an asp.net page that initially displays some data in a gridview with pagination(with a dataset as its datasource). And, there are few textboxes to perform insertions or updations ( don't ask about the edit/insert options in the gridview itself!!).
I need few guidances regarding the right place to store datasets.
Im posting the simplified codebehind file, that uses viewstate to store the dataset, which I dont like.
enter code here
class xyx : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridBind();
}
}
protected void InsertUpdateButton_Click(object sender, EventArgs e)
{
1.perform insert or update data in the database
2.GridBind();
}
protected void GridView1_PageIndexChanged(object sender, EventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.SelectedIndex = -1;
GridView1.DataSource = (DataSet)ViewState["DataSet"];
GridView1.DataBind();
}
private void GridBind()
{
DataSet ds = getDataFromDataBase();
GridwView1.DataSource = ds;
GridView1.DataBind();
ViewState["DataSet"] = ds;
}
}
Now apart from viewstate, what is the best choice to store the datasets??...
get the data from database everytime
Use a common Session variable Session["DataSet"] for all the datasets across all the pages(I have a few other pages with the same scenario )
Use Cache
I included session or cache because it is likely that the user might just be viewing the data rather than inserting or updating.
Also, In the Button click event instead of calling GridBind(), is it OK if I just updated the dataset in the viewstate rather than fetching data again from the database?
like -
DataSet ds = ViewSate["DataSet"] (or) Session["DataSet"] (or) Cache["DataSet"];
(perform updations or insertions upon the dataset)
Session(or)Cache(or)ViewState["DataSet"] = ds;
Generally:
If the data must be up to date, fetch it every time
If stale data is OK (or doesn't change often):
If the data is different per user, store in Session
If the data is the same for all users, use Cache or Application
If you wish to store large amounts of data per user do not use Session - you could run out of memory.
Depends upon many condition you should take care of these things first
Number of records in dataset.
Number of users.
If there are thousand of record then fetch only those record required. User some pager control.
here is an expample
For better use of paging.

How to pass variable from page to another page in ASP.NET

I want to ask how to pass a variable from a page to another page.
example.
in (page1.aspx.cs) there is button click and textbox
protected void Button1_Click(object sender, EventArgs e)
{
textbox1.text = ;
}
in (page2.aspx.cs)
A = "hello"
// A is variable that can be change, A variable is coming from microC
What I want is show "hello" from page2 in textbox1.text when I click button1 in page1.aspx
You can pass the value as a querystring parameter.
So if you are using Response.Redirect you could do something like
protected void Button1_Click(object sender, EventArgs e){
Response.Redirect("Page2.aspx?value=" + taxtbox1.text);
}
On Page 2 you can get the value using Request["value"].ToString()
Notice that the querystring parameter name is what you request. So if you have ?something=else you will Request["something"]
One way is to place the value into some form of temporary storage: Cookie, Session, etc. And then redirect.
Another would be to redirect with a query string value. It really depends on your situation.
I'd recommend setting a session if this is necessary.
Session["sessionname"] = "";
Though it isn't ideal, is it possible to have everything on page1? You can switch with a panel control.
Without a Postback it is not possible!
With a Postback, yes it is (see Cross Page Postback). Also see in the link what you can have access to! (Access possibilities are page controls & public members).
Other options, Session variables, cookies, query string, etc!
u can use one of this ways:
1- Query string
page.aspx?ID=111&&Name=ahmed
2- Session
Session["session1"] = "your value";
3- Public property
public String prop1
{
get
{
return txt_Name.Text;
}
}
4- Controls Data
5- HttpPost

How to retain field values on error in a dynamic gridview?

I have a page which has a GridView on it, which is populated from a database. Some of the columns in the GridView have text boxes, as well as Checkboxes.
When the user saves the page, the page may error if they have not entered their data correctly. At this point, I need to re-display what they have entered already so they can simply make the correction instead of having to change everything from scratch again.
The part that I'm having trouble with is the fact that this GridView can have a variable number of rows, so in turn a variable number of fields. What would be a good way to retain those values?
e.Cancel = true; will do the trick
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
e.Cancel = true;
//Display Message here
}

Resources