Setting viewstate on postback - asp.net

I am trying to set a ViewState-variable when a button is pressed, but it only works the second time I click the button. Here is the code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
lblInfo.InnerText = String.Format("Hello {0} at {1}!", YourName, DateTime.Now.ToLongTimeString());
}
}
private string YourName
{
get { return (string)ViewState["YourName"]; }
set { ViewState["YourName"] = value; }
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
YourName = txtName.Text;
}
Is there something I am missing? Here is the form-part of the design-file, very basic just as a POC:
<form id="form1" runat="server">
<div>
Enter your name: <asp:TextBox runat="server" ID="txtName"></asp:TextBox>
<asp:Button runat="server" ID="btnSubmit" Text="OK" onclick="btnSubmit_Click" />
<hr />
<label id="lblInfo" runat="server"></label>
</div>
</form>
PS: The sample is very simplified, "use txtName.Text instead of ViewState" is not the correct answer, I need the info to be in ViewState.

Page_Load fires before btnSubmit_Click.
If you want to do something after your postback events have fired use Page_PreRender.
//this will work because YourName has now been set by the click event
protected void Page_PreRender(object sender, EventArgs e)
{
if (Page.IsPostBack)
lblInfo.InnerText = String.Format("Hello {0} at {1}!", YourName, DateTime.Now.ToLongTimeString());
}
The basic order goes:
Page init fires (init cannot access ViewState)
ViewState is read
Page load fires
Any events fire
PreRender fires
Page renders

Related

Change session variable for all clicks except for one button in a page

I have got 10 button/Links in aspx page. I need to maintain a session variable on only ONE button click and for all other 9 click/action I need to change the value in session variable.
How can I get this in a best way, instead of writing in those 9 click actions.
Please suggest
You can re-use the same event for multiple buttons, and check the 'sender' to see which button was clicked.
Markup:
<asp:Button ID="Button1" runat="server" OnClick="GenericButtonClick" Text="Button" />
<asp:Button ID="Button2" runat="server" OnClick="GenericButtonClick" Text="Button" />
CS:
protected void GenericButtonClick(object sender, EventArgs e)
{
Button button = sender as Button;
switch(button.ID)
{
case "Button1":
//Maintain Session Variable
break;
default:
//Change Value in Session Variable
break;
}
}
You then set all your buttons to use the same event handler
I use mostly the command event handler instead of click, so in aspx side, you would have something like this:
<asp:Button ID="Button1" runat="server" OnCommand="DoSomething" CommandName="SetSession" CommandArgument="true" />
<asp:Button ID="Button2" runat="server" OnCommand="DoSomething" CommandName="SetSession" CommandArgument="false" />
<asp:Button ID="Button3" runat="server" OnCommand="DoSomething" CommandName="SetSession" CommandArgument="false" />
And in the back end cs file, there would be only one event handler like this:
protected void DoSomething(object sender, CommandEventArgs e)
{
if (e.CommandArgument.ToString() == "true")
{
// set session
}
}
The benefit of using CommandEventHandler is that even later on you change the button to ImageButton or LinkButton, you don't need to change the event signature, it works for all.
You can make a property in which you can set the session value and you can also get value from this property. I have made it private because it is used only in that page where you need.
private static string SetGetSession
{
set { HttpContext.Current.Session["Mairaj"] = value; }
get { return HttpContext.Current.Session["Mairaj"].ToString(); }
}
Here is how you can use it
protected void btnOne_Click(object sender, EventArgs e)
{
SetGetSession = "Mairaj";
}
protected void btnTwo_Click(object sender, EventArgs e)
{
SetGetSession = "Ahmad";
}
protected void btnTh_Click(object sender, EventArgs e)
{
SetGetSession = "Minhas";
}
If you want it to be used in other pages as well you can make a class and make this property public you will be able to access it everywhere.

Repeater with Buttons doesn't fire OnItemCommand even when DataBind doesn't happen when IsPostBack is true

I've got an image button in a Repeater, which is in a User Control, and I can't get the OnItemCommand event to fire when I click it. It always gives the error: "... Invalid postback or callback argument. Event validation is enabled using ..."
When I change the image button to a link button, it doesn't give me the error, but it still doesn't fire the OnItemCommand function.
I found some other relevant answers (such as How to process events from Buttons inside Repeaters? And what's this EnableEventValidation thing?) but they all say, "Make sure you're data-binding your repeater inside of a if(!Page.IsPostBack) block." I have done that, but it didn't make a difference.
Here's the markup for the repeater:
<asp:Repeater ID="rptExpenses" OnItemDataBound="rptExpenses_ItemDataBound" OnItemCommand="Button_Command" runat="server" >
<ItemTemplate>
<asp:ImageButton ID="ibDelete" ImageUrl="~/Images/delete.png" CommandName="Delete" runat="server" />
</ItemTemplate>
</asp:Repeater>
Here's some exerpts from the code-behind
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
rptExpenses.DataSource = ExpenseIds;
rptExpenses.DataBind();
}
}
protected void rptExpenses_ItemDataBound(object sender, RepeaterItemEventArgs e) {
if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem)) {
var ibDelete = (ImageButton)e.Item.FindControl("ibDelete");
ibDelete.CommandArgument = e.Item.DataItem.ToString();
}
}
protected void Button_Command(object sender, EventArgs e) {
var btn = (IButtonControl)sender;
switch (btn.CommandName) {
case "Delete":
//delete it
break;
}
}
Try using this code instead:
<asp:Repeater ID="rptExpenses" runat="server">
<ItemTemplate>
<asp:ImageButton ID="ibRemove" ImageUrl="~/Images/delete.png" runat="server"
CommandName="Remove"
CommandArgument='<%# Container.DataItem %>'
OnCommand="ibRemove_Click"/>
</ItemTemplate>
</asp:Repeater>
And this in the code behind:
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
rptExpenses.DataSource = ExpenseIds;
rptExpenses.DataBind();
}
}
protected void ibRemove_Click(object sender, CommandEventArgs e)
{
var btn = (IButtonControl)sender;
switch (btn.CommandName)
{
case "Remove":
//delete it, use btn.CommandArgument to find id to remove
break;
}
}
If you still receive the ... Invalid postback or callback argument. Event validation is enabled using ... error, it most likely means that you are somewhere re-binding the repeater before the ibRemove_Click(...) event is raised.
I found the reason why this was happening in the answer to this question: Why ItemCommand doesn't fired on My Repeater
Turns out that for some reason the Page's DataBind function was invalidating the repeater's controls without passing through the repeater's OnItemDataBound function a second time.

C# - Event handler for dynamic buttons

I have a textbox and submit button created using the design mode.
When the submit button is pressed, it will retrieve the user input from the textbox and then make a query to my database.
It will then display a list of dynamic buttons according to the information retrieved from my database.
However, the event handler for the buttons does not fire when clicked. I guess my problem is the postback but I cannot create those buttons in page_load etc. because I need to get the user input (from the textbox when submit button is pressed) before i can load the buttons.
How can i solve this problem?
Thank you.
Edit (codes):
protected void subBtn_Click(object sender, EventArgs e)
{
//database setup codes
.......
while (reader.Read())
{
Button detailsBtn = new Button();
detailsBtn.Text = reader["fName"].ToString();
//doesn't fire
detailsBtn.Click += new EventHandler(detailsBtn_Click);
memPanel.Controls.Add(detailsBtn);
}
}
Main problem is Postback regenerate dynamic controls on each postback if those controls does not exists.
For quick demo see this code
ASPX CODE
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<asp:Panel ID="pnl" runat="server"></asp:Panel>
</form>
ASPX.CS CODE
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
generate();
}
}
public void generate()
{
if (!pnl.HasControls())
{
for (int i = 0; i < 4; i++)
{
Button detailsBtn = new Button();
detailsBtn.Text = "fName" + i.ToString();
detailsBtn.ID = i.ToString();
detailsBtn.Click += new EventHandler(detailsBtn_Click);
pnl.Controls.Add(detailsBtn);
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
generate();
}
protected void detailsBtn_Click(object sender, EventArgs e)
{
}
Sound to me like you could easily refactor your page to use a simple <asp:Repeater runat="server" ..></asp:Repeater> instead of dynamically adding controls to a Panel.
Here is a very simple complete sample:
RepeaterTest.aspx
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="Server">
<asp:TextBox ID="theTextBox" runat="server"></asp:TextBox>
<asp:Button ID="theButton" runat="server" OnClick="theButton_Click" Text="Click me" />
<asp:Repeater ID="test" runat="server">
<ItemTemplate>
<asp:Button ID="theRepeaterButton" runat="server" Text='<%# Eval("fName") %>' OnClick="theRepeaterButton_Click" />
</ItemTemplate>
</asp:Repeater>
</asp:Content>
RepeaterTest.aspx.cs
public partial class RepeaterTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void theButton_Click(object sender, EventArgs e)
{
string filter = theTextBox.Text;
// below row simulates fetching data using the filter text in the text box
var data = Enumerable.Range(0, 20).Select(i => new { fName = filter + " " + i });
test.DataSource = data;
test.DataBind();
}
protected void theRepeaterButton_Click(object sender, EventArgs e)
{
var button = (Button)sender;
// do something here based on text/commandname/commandargument etc of the button
}
}

Ajax CalendarExtender, How to get the date after i click on a button?

I want to add add an Ajax CalendarExtender to my page. And then after selecting a date and clicking on a button I get the selected Day in a label.
I have a text box which is the target of the CalendarExtender
<asp:TextBox ID="DateText" runat="server" ReadOnly="true" ></asp:TextBox>
<ajaxToolkit:CalendarExtender
ID="Calendar1"
runat="server"
TargetControlID="DateText"
Format="MMMM d, yyyy"
PopupPosition="Right"
/>
<asp:Button runat="server" ID="Button1" onclick="Button1_Click" />
In the Code Behind:
On the first page load I set the date to Today.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Calendar1.SelectedDate = DateTime.Today;
}
}
In the Button1_Click Event
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = Calendar1.SelectedDate.Value.Day.ToString();
}
The problem is when I click the button (or after any post backs) the value selected get reset to Today's date.
And if I don't set it to DateTime.Today in the Page_Load It get reset to null and throw a null exception.
How can I solve this?
Thank you very much for any help.
I hope i was clear
Maybe this will work:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if(!Calendar1.SelectedDate)
Calendar1.SelectedDate = DateTime.Today;
}
}
The solution to the issue is making use of Request.Form collections. As this collection has values of all fields that are posted back to the server and also it has the values that are set using client side scripts like JavaScript.
Thus we need to do a small change in the way we are fetching the value server side.
C#
protected void Submit(object sender, EventArgs e)
{
string date = Request.Form[txtDate.UniqueID];
}

Information disappears on button click

I have a ListView that has a FileUpload control and a button in each ListViewItem.
I have an OnClick event on my button where i try and pull information from the FileUpload control, but when I try to access the control all of the values that were set are gone (FileName etc).
What do I need to do differently here to access the information I just entered?
<asp:ListView ID="lv_Uploads" runat="server" OnItemDataBound="GetThumbs" EnableViewState="true" >
<LayoutTemplate>
<div id="itemPlaceholder" runat="server" />
</LayoutTemplate>
<ItemTemplate>
<div style="width:500px;>
<asp:FileUpload runat="server" ID="fu_Upload" />
<asp:Button ID="btn_Save" runat="server" Text="Save File" OnClick="SaveFile" />
<br />
</div>
</ItemTemplate>
</asp:ListView>
Code behind:
protected void SaveFile(object sender, EventArgs e)
{
//This always evaluates to an empty string...
string myFile = ((FileUpload)((Button)sender).Parent.FindControl("fu_Upload")).FileName;
}
I tested the code you provided for the aspx and the following as the code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
lv_Uploads.DataSource = data;
lv_Uploads.DataBind();
}
}
protected void SaveFile(object sender, EventArgs e)
{
//This always evaluates to an empty string...
string myFile = ((FileUpload)((Button)sender).Parent.FindControl("fu_Upload")).FileName;
}
protected void GetThumbs(object sender, ListViewItemEventArgs e)
{
}
protected IEnumerable<string> data = new string[] { "test1", "test2", "test3" };
The FileUpload control had data for me on PostBack.
Are you using an UpdatePanel around the ListView? FileUpload controls are not compatible with UpdatePanels.
See:
FileUpload control inside an UpdatePanel without refreshing the whole page?
and
http://msdn.microsoft.com/en-us/library/bb386454.aspx#UpdatePanelCompatibleControls
Is the ListView control being rebound before SaveFile is fired on PostBack? If so, it would wipe out any values the user entered.

Resources