How to Pass Variables in ASP.NET PostBack? - asp.net

I'm trying to pass variables back to an ASP.NET web page by PostBack. The status variables for button presses are stored in ViewState. The problem here is that I need to press the button twice before the changed status is sent to the page.
The ViewState is read by Page_Load:
protected void Page_Load (object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["Print"] = "Small";
Response.Write ("Status: " + ViewState["Status"].ToString());
}
else
Response.Write ("Status: " + ViewState["Status"].ToString());
}
The ViewState for a button press is set by:
protected void ImageButton_LargeStatus_Click (object sender, ImageClickEventArgs e)
{
ViewState["Status"] = "Large";
}
Why do I need to press the ImageButton twice to change the ViewState?
Thanks.

Because 1st time you are updating ViewState with wrong key...
Replace below line
ViewState["Print"] = "Small";
with
ViewState["Status"] = "Small";

Related

ASP.NET buttonclick called after master page load when trying to create session

I am trying to create a session when a user clicks a button. I want to update controls on the master.aspx page after the session is created from the login button being clicked. However the master.aspx page_load is being called before the button click function. Any ideas on how I could work around this?
Default.aspx.cs
protected void ButtonLoginIn_Click(object sender, EventArgs e)
{
Session["username"] = "Joe";
}
Master.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (Session["username"] == null)
{
LinkLoginInOut.Text = "Sign In";
}
else
{
string sessionId = Session["username"].ToString();
LabelDbUserName.Text = "Joe";
LinkLoginInOut.Text = "Log Out";
}
}
You can simply use FindControl on the Master
LinkButton lb = Master.FindControl("LinkButton1") as LinkButton;
lb.Text = "LinkButton Master";
You can try to move the code in the Page_Load event of the masterpage to an event, that is called after the button_click event. That way the changes to the session occur before the updating of the masterpage. You can try the Page_LoadComplete event. Please check the "asp.net page life cycle" documentation for the sequence, in which the different page events are called.

How to update CheckBoxes on the client side after making changes on the server side?

I have a DropDownList and a CheckBox on my web form. After the DropDownList is clicked and this event is posted back to the server. DropDownList_SelectedIndexChanged event is called on the server side. Inside that event handler, I have CheckBox.Checked = true, But I couldn't make the page on the client side to reflect this change (CheckBox.Checked = true). How do I achieve this? Or am I in the wrong direction to use the DropDownList's event handler to update the CheckBox because the page firstly reloads and then DropDownList_SelectedIndexChanged is called?
Page load method:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.DropDownList1.Items.Clear();
AddItemsToDropDownList();
}
}
DropDownList selected index changed event handler:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
var selected = this.DropDownList1.SelectedItem.Text;
CheckBox checkBox = GetCheckBoxToBeSetByText(selected);
checkBox.Checked = true;
}
OK. Found the issue. Actually there is nothing wrong with the code in my original post. But to make a smallest sample when I posted, I removed some "extra" code. The below is the "complete" code (OK, fine, I still removed some code). As you can see, I put the CheckBox into a static Dictionary. Each time the SelectedIndexChanged event handler is called, it's modifying the CheckBox in that static Dictionary, which means it's modifying the CheckBox object created from the last session? (still not clear here) Looks like each time when a postback message is received, a new set of CheckBox objects are created. Bear with me if this is known to everybody here already because I only have two days of experience on this web development thing up to today.
private static Dictionary<Environment, CheckBox> EnvironmentsCheckBoxes;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
EnvironmentsCheckBoxes = new Dictionary<Environment,CheckBox>();
EnvironmentsCheckBoxes.Add(Environment.Dev1, this.Dev1_CheckBox);
EnvironmentsCheckBoxes.Add(Environment.Dev2, this.Dev2_CheckBox);
EnvironmentsCheckBoxes.Add(Environment.QA, this.QA_CheckBox);
EnvironmentsCheckBoxes.Add(Environment.QA2, this.QA2_CheckBox);
EnvironmentsCheckBoxes.Add(Environment.Demo, this.Demo_CheckBox);
EnvironmentsCheckBoxes.Add(Environment.Prod, this.Prod_CheckBox);
EnvironmentsCheckBoxes.Add(Environment.UAT, this.UAT_CheckBox);
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
var selected = this.DropDownList1.SelectedItem.Text;
if (selected == "Dev1")
{
EnvironmentsCheckBoxes[Environment.Dev1].Checked = true;
}
else if (selected == "Dev2")
{
...
}
...
}

User input is overridden by page_load during cross page postback

1the source page has a page load method like below:
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Text = DateTime.Today.AddDays(1).ToShortDateString();
}
it will result a textbox1.text to display tomorrow's date when the source page is rendered. I have this source page cross post back to a target page, and in the target page load event i have
if (Page.PreviousPage != null && PreviousPage.IsCrossPagePostBack == true)
{
TextBox SourceTextBox1 = (TextBox)Page.PreviousPage.FindControl("TextBox1");
if (SourceTextBox1 != null)
{
Label1.Text = SourceTextBox1.Text;
}
}
the problem is if the user changes the content of textbox1, supposely, the label1 on target page should catch the user input and display it, but now it only displays whatever i set in the source page load event. I understand the self page post back life cycle, but this is cross page post back. IMO, the source page load event has nothing to do with this, but why it overrides the user input?? Any idea.
Just surround this with a if(!IsPostBack) check:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
TextBox1.Text = DateTime.Today.AddDays(1).ToShortDateString();
}
}
Otherwise the value will be overwritten on every postback. So when you Server.Transfer it to the other page it is already changed.

How can this codebehind be written better?

I have a form which has a single textbox that sends some data to the database upon hitting enter. Data is displayed below the textbox in a repeater control. Input data is displayed on the form immediately by binding the data to the repeater in the TextChanged event of that textbox.
In the CodeBehind, I am calling BindRepeater method twice, once on every new page load and once on the TextChanged event of the textbox.
How can this be rewritten to call the BindRepeater only once and still achieve the same effect?
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
BindRepeater();
}
}
protected void BindRepeater()
{
// data retrieval
// repeater binding
}
protected void CreateData(string newdata)
{
// data insert
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
if (TextBox1.Text != string.Empty)
{
string _newData = TextBox1.Text.Trim();
CreateData(_newData);
BindRepeater();
}
}
Use an event that would be fired after the text changed event to do the binding in. you can now remove it from the page load event.

Get the row that has been clicked in the gridview

I have added OnClick event dynamically for gridview.So when I click on any of the row on grid view, the event is fired but I can't get which row is clicked.
This is the code where I add event.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Attributes["OnClick"] = Page.ClientScript.GetPostBackClientHyperlink(btnGrid, string.Empty);
}
//This is the code which catches this event
protected void GridView1_OnClick(object sender, EventArgs e)
{
_ID="10" //Static data. I need this from the gridview1.row[ClickedRow].cell[0]
}
I fear you'll have to "manually" assign this value.
For this, add hidden input element to the form:
<input type="hidden" name="clicked_row" />
Change the code to:
e.Row.Attributes["OnClick"] = Page.ClientScript.GetPostBackClientHyperlink(btnGrid, string.Empty) + "; document.forms[0].elements['clicked_row'].value = '" + e.Row.RowIndex + "';";
And finally, read the index from the Request in the GridView1_OnClick method:
_ID = Int32.Parse(Request.Form["clicked_row"]);
If each row has its own ID change e.Row.RowIndex to e.Row.Id.
I think, you could pass your id/rowindex as parameter to GetPostBackClientHyperlink() and implement the IPostBackEventHandler-interface in your page. The RaisePostBackEvent() method will get the id as input parameter passed in.
I haven't tested this, I just took a look at the example in MSDN documentation
Try passing in the row instead of the grid, like this:
e.Row.Attributes["OnClick"] = Page.ClientScript.GetPostBackClientHyperlink(e.Row, String.Empty);
And in your event handler:
protected void GridView1_OnClick(object sender, EventArgs e)
{
if (sender is GridViewRow)
{
int index = ((GridViewRow)sender).RowIndex;
}
}
I'm not positive, but I think the GridView OnClick will still fire since you're passing a child element of the grid.

Resources