How to change view-state value dynamically? - c#

I have textbox and button controls in my page. For textbox I have enabled view state, page-load event I am setting text box value “Hello Mr!”. Now I want to change the view state value for text box to “Hello Mr Pradeep!” when post back occurs, how can I do that? And in which all page events I can do that.
<asp:TextBox ID="TextBox1" runat="server" EnableViewState= "true"/>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Button" />
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Text = "Hello Mr!";
}
Thanks,
Pradeep

As far as i understand your question you can do this using javascript on page load event

Your page is retrieving viewstate between the init of the page and just before the page load event. So the more early attempt you can make to change the view State is in the page load.
Because if you were to modify it before its retrieving your changes would be lost.
protected override void OnInit(EventArgs e)
{
if (IsPostBack)
{
//on postback ViewSate["test"] is null
ViewState["test"] = "Valuepostback";
//Now ViewSate["test"] is Valuepostback
}
base.OnInit(e);
}
protected override void OnLoad(EventArgs e)
{
if (IsPostBack)
{
//on postback ViewState has been reloaded from the page sent and therefore the initial value set in the oninit does not exists anymore
//ViewState["test"] is MyValue
//if you want to cahnge specifically the view state do it here
}
if (!IsPostBack)
ViewState["test"] = "MyValue";
base.OnLoad(e);
}

Related

Redirecting to previous page by avoiding required field validation

i have 3 pages
Login
Home
Add employeeNow i've a back button in "Add Employee" page which should redirect to the previous page! but when i click on it the required field validators will turn on!! how can i avoid that for back button? I tried using two types of code but both gets stuck in there for validation.
protected void Button2_Click(object sender, System.EventArgs e)
{
string prevPage = Request.UrlReferrer.ToString();
Response.Redirect(prevPage);
}
And this
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("home.aspx");
}
On aspx Page you need to set CausesValidation = false for back button. See below
<asp:Button ID="btnBack" runat="server" CausesValidation="false" Text="Back" />
By Adding CausesValidation = false. The Validation event will not fire for that button click and your redirect will work properly.
Hope that helps

Input text box value is not changing

In my .aspx page I have a 'input' html tag, also an asp button.
<input id="Name" type="text" runat="server" clientidmode="Static" />
<asp:Button Width="100" type="submit" ID="sendOrder" runat="server" OnClick="SubmitForm" Text="Submit" />
On page load, I am filling the value in input tag from code behind, like this:
Name.Value= "X";
But now if I change value of this text box from browser, lets say "Y", and click on Submit button, then I get the old value, but not the new one.
protected void SubmitForm(object sender, EventArgs e)
{
var test= Name.Value; // here I get old value
}
How can I get the altered value?
Make sure you are only setting the value to "X" when its not a postback:
if (!Page.IsPostBack){
Name.Value= "X";
}
Otherwise when clicking the submit button, the Page_Load() event will change the value from "Y" back to "X".
You need to use !IsPostBack on Page_Load shown as below:
protected void Page_Load(object sender, EventArgs e)
{
//it's important to use this, otherwise textbox old value overrides again
if (!IsPostBack)
{
Name.Value= "X";
}
}
Suggestion:
We can use use <input></input> control in asp.net but best practice is to use <asp:TextBox></asp:TextBox> control instead.
Here is the sample example:
HTML
<asp:TextBox ID="Name" runat="server"></asp:TextBox>
<asp:Button Width="100" ID="sendOrder" runat="server" OnClick="SubmitForm"
Text="Submit" />
Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
//it's important to use this, otherwise textbox old value overrides again
if (!IsPostBack)
{
Name.Text = "Some Value";
}
}
protected void SubmitForm(object sender, EventArgs e)
{
var test = Name.Text; //now get new value here..
}
Check for IsPostback in Page_Load so you don't overwrite the values that are submitted!
You don't need all the else portion, just do this
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//code to execute here only when an action is taken by the user
//and not affected by PostBack
}
//these codes should be affected by PostBack
}

How To Pass Textbox Value Present In UserControl To Aspx Page Label By Clicking Button In UserControl

TestUC.ascx Design Code
<asp:TextBox ID="txtbox1" runat="server" ClientIDMode="Static" placeholder="Enter Some Text" ></asp:TextBox><br />
<asp:Button ID="btn1" runat="server" Text="Click" OnClick="btn1_Click" ClientIDMode="Static" />
Test.aspx Page Code
<%# Register Src="~/WebUserControls/TestUC.ascx" TagName="WebUserControlTest"
TagPrefix="uctest" %>
<asp:Content ID="Content1" ContentPlaceHolderID="cphBody" runat="server">
<asp:Label ID="lbl1" runat="server" >Label</asp:Label>
<uctest:WebUserControlTest ID="ucTest" runat="server"></uctest:WebUserControlTest>
</asp:Content>
OutPut:
I Need ..
Step1: Enter Some text In Text Box
Step2:Then I Click Click Button
[Note: This Two Controls Are Bind From UserControl]
Step3:What Text Entered in TextBox Is Show In label [Note Label Present In Aspx Page]
You will need to have a custom event & you will also need to expose the Text property of the TextBox in your UserControl, like this.
public partial class YourUserControl : UserControl
{
public String Text
{
get
{
return this.txtBox1.Text;
}
//write the setter property if you would like to set the text
//of the TextBox from your aspx page
//set
//{
// this.txtBox1.Text = value;
//}
}
public delegate void TextAppliedEventHandler(Object sender, EventArgs e);
public event TextAppliedEventHandler TextApplied;
protected virtual void OnTextApplied(EventArgs e)
{
//Taking a local copy of the event,
//as events can be subscribed/unsubscribed asynchronously.
//If that happens after the below null check then
//NullReferenceException will be thrown
TextAppliedEventHandler handler = TextApplied;
//Checking if the event has been subscribed or not...
if (handler != null)
handler(this, e);
}
protected void yourUserControlButton_Click(Object sender, EventArgs e)
{
OnTextApplied(EventArgs.Empty);
}
}
Then in your aspx page, where you have placed YourUserControl (OR you are dynamically adding it from the code behind), you can subscribe to this event like this.
protected void Page_Load(Object sender, EventArgs e)
{
if (!IsPostBack)
{
yourUserControl.TextApplied += new YourUserControl.TextAppliedEventHandler(yourUserControl_TextApplied)
}
}
You can use the custom event of the user control in your page like this.
protected void yourUserControl_TextApplied(Object sender, EventArgs e)
{
yourLabelInYourPage.Text = yourUserControl.Text;
}
And you are done...
EDIT : You can rename the Controls & Events as you like. I have used the names only for the example purpose.
EDIT : In website projects, if you want to add your user control dynamically then,
you might need to include the namespace ASP in your page, like this.
using ASP;
And add this Directive in your page in the aspx markup.
<%# Reference Control="~/PathToYourUserControl/YourUserControl.ascx" %>
other solution : create an event in the usercontrol, which is called in the button click.
Subscribe to this event in the codebehind of the aspx page. that way you can update your interface only if a value is provided.
a little more complicated, but you could re-use this logic to more complex control / parent control feature in the future.
i can add code snippet if asked
This Answer Is Prepared By Help Of #Devraj Gadhavi i Edited Some Code .
UserControl Page Design Code
<asp:TextBox ID="txtbox1" runat="server" ClientIDMode="Static" placeholder="Enter Some Text" ></asp:TextBox><br />
<asp:Button ID="btn1" runat="server" Text="Click" OnClick="btn1_Click" ClientIDMode="Static" />
UserControl Page Code
public partial class TestUC : System.Web.UI.UserControl
{
public String Text
{
get
{
return this.txtbox1.Text;
}
}
public delegate void TextAppliedEventHandler(Object sender, EventArgs e);
public event EventHandler TextApplied;
protected virtual void OnTextApplied(EventArgs e)
{
if (TextApplied != null)
TextApplied(this, e);
}
protected void btn1_Click(object sender, EventArgs e)
{
OnTextApplied(EventArgs.Empty);
}
}
Aspx Page Design Code
<%# Register Src="~/WebUserControls/TestUC.ascx" TagName="WebUserControlTest"
TagPrefix="uctest" %>
<asp:Content ID="Content1" ContentPlaceHolderID="cphBody" runat="server">
<asp:Label ID="lbl1" runat="server" >Label</asp:Label>
<uctest:WebUserControlTest ID="ucTest" runat="server"></uctest:WebUserControlTest>
</asp:Content>
Aspx Cs File Code
public partial class Test2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ucTest.TextApplied += new EventHandler(ucTest_TextApplied);
}
protected void ucTest_TextApplied(Object sender, EventArgs e)
{
lbl1.Text = ucTest.Text;
}
}
Another method ,If you don't want to expose the Text property of the TextBox in your UserControl Just use method "UserControl.FindControl("Id Of your Textbox which is present in user control")" in your Case WebUserControlTest.FindControl("txtbox1").
And below is the simpler way to register an event handler on the parent web form's code behind.
Code goes as below for parent form asxp.cs
protected override void OnInit(EventArgs e)
{
//find the button control within the user control
Button button = (Button)WebUserControlTest.FindControl("btn1");
//wire up event handler
button.Click += new EventHandler(button_Click);
base.OnInit(e);
}
void button_Click(object sender, EventArgs e)
{
TextBox txt = (TextBox) WebUserControlTest.FindControl("txtbox1");
//id of lable which is present in the parent webform
lblParentForm.Text=txt.text;
}
Also, you can achieve this using JavaScript like below (given your code above):
<script type="text/javascript">
function getUCTextboxValue() {
let txtName = document.getElementById('<%=ucTest.FindControl("txtbox1").ClientID %>');
let lbl = document.getElementById('<%=lbl1.ClientID %>');
lbl.innerText = txtName.value
}
Also, from the parent page, you can add a HiddenField and save the textbox value on it (using the JavaScript code above) then catch its value from code behind.

Not able to visible button asp.net

I am not able to visible my button on another button click event.
.aspx
<asp:Button ID="btnActivate" runat="server" SkinID="skinLoginButton"
Text="Activate" ToolTip="Activate" CausesValidation="true"
ValidationGroup="UserAuthentication" onclick="btnActivate_Click" />
<asp:Button ID="btnhomepage" Visible="false" runat="server"
Text="Goto Homepage" CssClass="cssLoginButton" onclick="btnhomepage_Click"/>
.cs
#region btnActivate_Click
protected void btnActivate_Click(object sender, EventArgs e)
{
this.btnhomepage.Visible = true;
}
#endregion
I use this.btnhomepage.Visible = true; in .cs file.
what's wrong in my code or declearation?
<asp:Button ID="btnhomepage" Visible="false" runat="server"
Text="Goto Homepage" CssClass="cssLoginButton" onclick="btnhomepage_Click"/>
when using visible attribute in the mark-up you are forcing your control to be visible=false and stay false forever. asp.net engine render asp.net controls into html control in asp.net page life cycle at Render stage. even you had changed the control property in any code behind event
Solution: Don't use makup attribute when setting control behaviour dynamicllay
page life cycle link:
http://msdn.microsoft.com/en-us/library/ms178472(v=vs.100).aspx
http://www.codeproject.com/Articles/73728/ASP-NET-Application-and-Page-Life-Cycle
Remove the visible property from the btnhomepage button and make it invisible from Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
this.btnhomepage.Visible = false;
}
}
Try this
btnhomepage.Visible = true;
btnhomepage.Enabled = true;
btnhomepage.Style.Add("display", "block");

modal pop-up ok button not working as expected for a dropdown menu

CODE BEHIND:
private void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
{
ddlLanguage.SelectedValue = Thread.CurrentThread.CurrentCulture.Name;
}
}
protected void ddlLanguage_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlLanguage.SelectedValue == "es-ES")
{
mdlPopup.Show();
}
//Sets the cookie that is to be used by Global.asax
HttpCookie cookie = new HttpCookie("CultureInfo");
cookie.Value = ddlLanguage.SelectedValue;
Response.Cookies.Add(cookie);
//Set the culture and reload the page for immediate effect.
//Future effects are handled by Global.asax
Thread.CurrentThread.CurrentCulture = new CultureInfo(ddlLanguage.SelectedValue);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(ddlLanguage.SelectedValue);
//Server.Transfer(Request.Path);
}
protected void OKButton_Click(object sender, EventArgs e)
{
Server.Transfer(Request.Path);
}
ASPX PAGE:
<asp:DropDownList ID="ddlLanguage" class="langpnl" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="ddlLanguage_SelectedIndexChanged">
<asp:ListItem Value="en-US">Eng</asp:ListItem>
<asp:ListItem Value="es-ES">Esp</asp:ListItem>
</asp:DropDownList>
<ajaxToolkit:ModalPopupExtender ID="mdlPopup" runat="server" TargetControlID="testhidden"
PopupControlID="pnlPopup" OkControlID="OKButton" />
<asp:Panel ID="pnlPopup" runat="server" Width="500px" Style="display: none">
All content may not be in Spanish.
<asp:Button ID="OKButton" runat="server" Text="OK" OnClick="OKButton_Click" />
</asp:Panel>
<asp:HiddenField ID="testhidden" runat="server" />
I am trying to set the language as per the selection in the Dropdown box. But if the user selects spanish I want to display a popup modal with a msg & once the button OK is pressed I want to postback the whole page.
Currently I am able to display the popup but the page never refreshed so the language still doesn't change. In the code behind if I remove the server.transfer from the OK button and put it in the SelectIndexChange then the page postback is working but there is no popup masg .I think the page gets postback after the popup executes so it never gets displayed...please need some help I am breaking my head since last 3 days.
Define another button in that panel... and do whatever you want in his onclick event. So you will have a postback.
The OKButton click event... OKButton_Click will not fire as long as you assigned him in you modalpopup...
if (ddlLanguage.SelectedValue == "es-ES")
{
mdlPopup.Show();
}
else
{
Server.Transfer(Request.Path);
}
& removed the OK button from Modalpopup..finally got to see what I was Expecting..

Categories