Incrementing variables in ASP.net on every button click - asp.net

I want to increment date in every click ASP.NET.
But Every time the page posts back, it is essentially starting over from scratch - anything initialized to 0.
I need to persist a value across postbacks but I don't how to do that. I would appreciate for any help.
Here is what I'am trying to do:
int myNumber = 0;
protected void Button1_Click1(object sender, EventArgs e)
{
lblDate.Text = DateTime.Now.StartOfWeek(DayOfWeek.Monday).AddDays(myNumber).ToShortDateString();
myNumber++;
}
Update:
My finaly goal is to get next weeks first day with next button and Previous week, I mean I want to forword and backword...
public int NextCount
{
get { return ViewState["Count"] != null ? (int)ViewState["Count"] : 7; }
set { ViewState["Count"] = value; }
}
protected void btnNext_Click1(object sender, EventArgs e)
{
lblsum.Text = DateTime.Now.StartOfWeek(DayOfWeek.Monday).AddDays(NextCount).ToShortDateString();
NextCount = NextCount+7;
}
protected void btnPrevious_Click(object sender, EventArgs e)
{
lblsum.Text = DateTime.Now.StartOfWeek(DayOfWeek.Monday).AddDays(NextCount).ToShortDateString();
NextCount = NextCount - 7;
}
But When I click Prev button .. there is delay with one click after two or three Click then reaction coming the same with next button when you click from prev to next. Maybe I have to store it in session?

I have updated your code below by using ViewState to handle this. Other easiest option would be storing the same in Session, Cache or Cookie.
While storing a value in ViewState, it will create a hidden field
in the page and store the value to maintain it across the postback.
public int NextCount
{
get { return ViewState["NextCount"] != null ? (int)ViewState["NextCount"] : 0; }
set { ViewState["NextCount"] = value; }
}
protected void btnNext_Click1(object sender, EventArgs e)
{
NextCount = NextCount+7;
lblsum.Text = DateTime.Now.StartOfWeek(DayOfWeek.Monday).AddDays(NextCount).ToShortDateString();
}
protected void btnPrevious_Click(object sender, EventArgs e)
{
NextCount = NextCount - 7;
lblsum.Text = DateTime.Now.StartOfWeek(DayOfWeek.Monday).AddDays(NextCount).ToShortDateString();
}

Related

How to prevent to adding two lists in asp.net?

How to Prevent adding two controls or to lists ? I've tried this code but it doesn't work... Pease help!
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
ViewState["check"] = "First_Time";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (ViewState["check"] == "First_Time")
{
for (int i = 0; i < 6; i++)
{
CheckBoxList1.Items.Add(i.ToString());
}
ViewState["check"] = "Scond_Time";
}
else
{
Response.Write("Sorry, Can't create a list on second time");
}
}
The problem with your approach is that the button click event is triggered on postback, hence your postback check in Page_Load is pointless.
Since the CheckBoxList.Items are stored in Viewstate by default(it implements IStateManager), why don't you simply check if the items are already added?
protected void Button1_Click(object sender, EventArgs e)
{
if (CheckBoxList1.Items.Count < 6)
{
CheckBoxList1.Items.Clear();
for (int i = 0; i < 6; i++)
{
CheckBoxList1.Items.Add(i.ToString());
}
}
else
{
// don't use Response.Write to output messages but controls
Response.Write("Sorry, Can't create a list on second time");
}
}

Getting the index of the last row inserted in a GridView

How do I get the row index of the last row inserted in a GridView considering the user may have custom ordering in the grid (I can't use the last row).
protected void ButtonAdd_Click(object sender, EventArgs e)
{
SqlDataSourceCompleteWidget.Insert();
GridViewCompleteWidget.DataBind();
GridViewCompleteWidget.EditIndex = ??????;
}
I want to put the row into edit mode immediately after the insert occurs.
UPDATE
protected void ButtonAdd_Click(object sender, EventArgs e)
{
//SqlDataSourceCompleteWidget.InsertParameters.Add("EFFECTIVE_DATE", Calendar1.SelectedDate.ToString("yyyy-MM-dd"));
SqlDataSourceCompleteWidget.InsertParameters[0].DefaultValue = Calendar1.SelectedDate.ToString("yyyy-MM-dd");
SqlDataSourceCompleteWidget.Insert();
GridViewCompleteWidget.DataBind();
GridViewCompleteWidget.EditIndex = 1;
}
private int mostRecentRowIndex = -1;
protected void GridViewCompleteWidget_RowCreated(object sender, GridViewRowEventArgs e)
{
mostRecentRowIndex = e.Row.RowIndex;
//GridViewCompleteWidget.EditIndex = e.Row.RowIndex;
}
You would want to handle the RowCreated event. You can access the row data and identity/location using the GridViewRowEventArgs object that is passed to this event handler.
void YourGridView_RowCreated(Object sender, GridViewRowEventArgs e)
{
YourGridView.EditIndex = e.Row.RowIndex;
}
Edit using the gridview's onitemcommand. Then you can use a binding expression on the grid column to set whatever you want. If you are using a button or linkbutton or several others you could use the CommandArgument
CommandArgument='<%# Eval("DataPropertyIWant") %>'
Edit
Sorry I skipped that ordering was done by user. I've tested the following code and it works having respected the users ordering of items, but we must take the user to the page where the last row exists.
1st: Retrieve the Max(ID) from database after insertion, store it in a session
select Max(ID) from tbl_name; -- this statement can retrieve the last ID
Session["lastID"]=lastID;
2nd:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType==DataControlRowType.DataRow)
if (Session["lastID"] != null)
if ((int)DataBinder.Eval(e.Row.DataItem, "ID") == (int)Session["lastID"])
{
//Session["rowIndex"] = e.Row.RowIndex;
int rowIndex=e.Row.RowIndex;
if (Session["type"] != null)
if (Session["type"].ToString() == "Normal")
{
int integ;
decimal fract;
integ = rowIndex / GridView1.PageSize;
fract = ((rowIndex / GridView1.PageSize) - integ;
if (fract > 0)
GridView1.PageIndex = integ;
else if (integ > 0) GridView1.PageIndex = integ - 1;
GridView1.EditIndex = rowIndex;
}
}
}
3rd: Convert your commandField into TemplateFields and Set their CommandArgument="Command"
I'll use this argument to identify what triggered RowDataBound event. I store the value in a Session["type"]. The default value is "Normal" defined in the page load event.
if(!IsPostBack)
Session["type"]="Normal";
the other value is set in RowCommand event
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandArgument == "Command")
Session["type"] = "Command";
}
It works for me fine.
Sorry for my language and,may be, unnecessary details.
UPDATE: I worked off of this post
I'm assuming you just return a value after doing the insert but you can set ID wherever you insert the record.
private int mostRecentRowIndex = -1; //edit index
private bool GridRebound = false; //used to make sure we don't rebind
private string ID; //Is set to the last inserted ID
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
//Set so grid isn't rebound on postback
GridRebound = true;
}
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
SqlDataSourceCompleteWidget.InsertParameters[0].DefaultValue = Calendar1.SelectedDate.ToString("yyyy-MM-dd");
ID = SqlDataSourceCompleteWidget.Insert();
GridViewCompleteWidget.DataBind();
}
protected void GridViewCompleteWidget_RowDataBound(object sender, GridViewRowEventArgs e)
{
//Check that the row index >= 0 so it is a valid row with a datakey and compare
//the datakey to ID value
if (e.Row.RowIndex >= 0 && GridViewCompleteWidget.DataKeys[e.Row.RowIndex].Value.ToString() == ID)
{
//Set the edit index
mostRecentRowIndex = e.Row.RowIndex;
}
}
protected void GridViewCompleteWidget_DataBound(object sender, EventArgs e)
{
//Set Gridview edit index if isn't -1 and page is not a post back
if (!GridRebound && mostRecentRowIndex >= 0)
{
//Setting GridRebound ensures this only happens once
GridRebound = true;
GridViewCompleteWidget.EditIndex = mostRecentRowIndex;
GridViewCompleteWidget.DataBind();
}
}
Selects if inserting last record in gridview (no sorting)
You should be able to get the number of rows from the datasource: (minus 1 because the rows start at 0 and the count starts at 1)
GridViewCompleteWidget.EditIndex = ((DataTable)GridViewCompleteWidget.DataSource).Rows.Count - 1;
But put this before you bind the data:
protected void ButtonAdd_Click(object sender, EventArgs e)
{
SqlDataSourceCompleteWidget.Insert();
GridViewCompleteWidget.EditIndex = ((DataTable)GridViewCompleteWidget.DataSource).Rows.Count - 1;
GridViewCompleteWidget.DataBind();
}

How to do that fields not initialization?

how to do that every time s_Sort not update SortDirection.Desc
private SortDirection s_Sort = SortDirection.Desc;
protected void Page_Load(object sender, EventArgs e)
{
lblSort.Text = S_Sort.ToString();//every time == SortDirection.Desc - this is bad!
if (!IsPostBack)
{
ShowTree();
Validate();
}
}
Need
public void btnSortUp_Click(object sender, EventArgs e)
{
S_Sort = SortDirection.Asc;
}
public void btnSortDown_Click(object sender, EventArgs e)
{
S_Sort = SortDirection.Desc;
}
but after SortDirection.Desc is bad
The is a problem of the ASP.NET lifecycle. Every time a postback happens (for example, when btnSortUp or btnSortDown is clicked), a new instance of your page is created, i.e., S_Sort is reinitialized to Desc. If you want to persist the value between postbacks, you can store it in the viewstate, for example, by encapsulating it in a private property:
private SortDirection S_Sort {
get { return (SortDirection)(ViewState["S_Sort"] ?? SortDirection.Desc); }
set { ViewState["S_Sort"] = value; }
}

Textbox value null when trying to access it

namespace Dynamic_Controls.Dropdowndynamic
{
public partial class DropdowndynamicUserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (ControlCount != 0)
{
Recreatecontrols();
}
}
private void Recreatecontrols()
{
// createtextboxes(ControlCount);
createtextboxes(2);
}
protected void createtextboxes(int ControlCount)
{
DynPanel.Visible = true;
for (int i = 0; i <= ControlCount; i++)
{
TextBox tb = new TextBox();
tb.Width = 150;
tb.Height = 18;
tb.TextMode = TextBoxMode.SingleLine;
tb.ID = "TextBoxID" + this.DynPanel.Controls.Count;
tb.Text = "EnterTitle" + this.DynPanel.Controls.Count;
tb.Load+=new EventHandler(tb_Load);
tb.Visible = true;
tb.EnableViewState = true;
DynPanel.Controls.Add(tb);
DynPanel.Controls.Add(new LiteralControl("<br/>"));
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Int32 newControlCount = Int32.Parse(DropDownList1.SelectedValue);
//createtextboxes(newControlCount);
//ControlCount+=newControlCount;
createtextboxes(2);
}
protected void Button1_Click(object sender, EventArgs e)
{
readtextboxes();
}
public void readtextboxes()
{
string x = string.Empty;
for (int a = 0; a < DynPanel.Controls.Count; a++)
{
foreach (Control ctrl in DynPanel.Controls)
{
if (ctrl is TextBox)
{
x = ((TextBox)ctrl).Text;
}
x+=x+("\n");
}
Result.Text = x;
}
}
private Int32 ControlCount
{
get
{
if (ViewState["ControlCount"] == null)
{
ViewState["ControlCount"] = 0;
}
return (Int32)ViewState["ControlCount"];
}
set
{
// ViewState["ControlCount"] = value;
ViewState["ControlCount"] = 2;
}
}
private void tb_Load(object sender, EventArgs e)
{
LblInfo.Text = ((TextBox)sender).ID + "entered";
}
}
}
Are you adding these controls dynamically in Page_Load (by, I'm assuming, calling your AddRequiredControl() method)? If so, is it wrapped in a conditional which checks for IsPostBack? The likely culprit is that you're destructively re-populating the page with controls before you get to the button click handler, so all the controls would be present but empty (as in an initial load of the page).
Also, just a note, if you're storing each control in _txt in your loop, why not refer to that variable instead of re-casting on each line. The code in your loop seems to be doing a lot of work for little return.
You need to recreate any dynamically created controls on or before Page_Load or they won't contain postback data.
I'm not entirely clear what happens on DropdownList changed - are you trying to preserve anything that has been entered already based on the textboxes previously generated?
In any event (no pun intended) you need to recreate exactly the same textboxes in or before Page_Load that were there present on the postback, or there won't be data.
A typical way to do this is save something in ViewState that your code can use to figure out what to recreate - e.g. the previous value of the DropDownList. Override LoadViewState and call the creation code there in order to capture the needed value, create the textboxes, then in the DropDownList change event, remove any controls that may have been created in LoadViewState (after of course dealing with their data) and recreate them based on the new value.
edit - i can't figure out how your code works now, you have AddRequiredControl with parameters but you call it with none. Let's assume you have a function AddRequiredControls that creates all textboxes for a given DropDownList1 value, and has this signature:
void AddRequiredControls(int index)
Let's also assume you have a PlaceHolder called ControlsPlaceholder that will contain the textboxes. Here's some pseudocode:
override void LoadViewState(..) {
base.LoadViewState(..);
if (ViewState["oldDropDownIndex"]!=null) {
AddRequiredControls((int)ViewState["oldDropDownIndex"]);
}
}
override OnLoad(EventArgs e)
{
// process data from textboxes
}
void DropDownList1_SelectedIndexChanged(..) {
ControlsPlaceholder.Controls.Clear();
AddRequiredControls(DropDownList1.SelectedIndex);
ViewState["oldDropDownIndex"]=DropDownList1.SelectedIndex;
}

Control Add PostBack Problem

I Add Control Dynamiclly but; easc Postback event my controls are gone. I Can not see again my controls.
So How can I add control ?
Because you must recreate your controls on every postback,
see this article
Add the controls in the Page's Init event and they will be preserved in viewstate when posting back. Make sure they have a unique ID.
See this link...
ASP.NET Add Control on postback
A very trivial example..
public partial class MyPage : Page
{
TextBox tb;
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
tb = new TextBox();
tb.ID = "testtb";
Page.Form.Controls.Add(tb);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
//tb.Text will have whatever text the user entered upon postback
}
}
You should always assign a unique ID to the UserControl in its ID property after control is loaded. And you should always recreate UserControl on postback.
To preserve posback data (i.e. TextBox'es) you must load UserControl in overriden LoadViewState method after calling base.LoadViewState - before postback data are handled.
Add controls in runtime and save on postback:
int NumberOfControls = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["b1"] = 0;
}
else
{
if ((int)ViewState["b1"] > 0)
{
CreateBtn();
}
}
}
protected void btn1_Click(object sender, EventArgs e)
{
NumberOfControls = (int)ViewState["b1"];
Button b1 = new Button();
// b1.Attributes.Add("onclick", "x()");
b1.Text = "test2";
b1.ID = "b1_" + ++NumberOfControls;
b1.Click +=new System.EventHandler(btn11);
Panel1.Controls.Add(b1);
ViewState["b1"] = NumberOfControls;
}
protected void CreateBtn()
{
for (int i = 0; i < (int)ViewState["b1"];i++)
{
Button b1 = new Button();
// b1.Attributes.Add("onclick", "x()");
b1.Text = "test2";
b1.ID = "b1_" + i;
b1.Click += new System.EventHandler(btn11);
Panel1.Controls.Add(b1);
}
}
protected void btn11(object sender, System.EventArgs e)
{
Response.Redirect("AboutUs.aspx");
}

Resources