Get Set values of TextBox Control from server side - c#

Let say I have this code on Page load of ASP.NET Webform
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Text = "123";
}
and this is my control in aspx file
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
If I change the textbox data from 123 to 12548 or any thing in the front end and then I click the button
Now in this is my code behind button click event
protected void Button1_Click(object sender, EventArgs e)
{
string s = TextBox1.Text;
}
Now in TextBox1.Text I should be getting 12548 or updated value instead I am getting 123 which I have already set in page load.
Now I want to get the updated value, how may I do it the right way.

Wrap it in a NOT is Postback
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
TextBox1.Text = "123";
}
}
or remove it completely:
protected void Page_Load(object sender, EventArgs e)
{
//not here
}
<asp:TextBox ID="TextBox1" Text="123" runat="server"></asp:TextBox>

Modify the Page_Load as follows:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostback)
{
TextBox1.Text = "123";
}
}

The problem was this "In ASP.Net every time you cause a postback of any kind, including handling events like button clicks, you're working with a brand new instance of your page class that must be rebuilt from scratch. Any work you've done previously to build the page on the server is gone. That means running the entire page life cycle, including your page load code, and not just the click code.
Every time you perform any event in the front end it will recreate the page and call the pageload method again and the page would be actually reset. To avoid it one should use the following code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostback)
{
//default code
}
}

Related

ASP.NET C# why cant I change the text in a textbox in a webpage

I have an ASP.NET project with a simple webpage.When I load the page the textbox display "Hello". When I click the "btnUpload" the text goes away.
I tried !IsPostBack in the Load_Form function gut the just make the text stay the same.
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Text = "Hello";
}
protected void btnUpload_Click(object sender, EventArgs e)
{
TextBox1.Text = "Good Bye";
}
This is because you have not used
if(!IsPostBack) { }
inside Page_load() method
so modify your code as:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack) {
TextBox1.Text = "Hello";
}
}
protected void btnUpload_Click(object sender, EventArgs e)
{
TextBox1.Text = "Good Bye";
}
Because, you have not used this, thats why, on the postback of button it changes the value to TextBox1.Text = "Good Bye"; but it follows completing the postback with Page_Load() so it changes it again to TextBox1.Text = "Hello"; that's the reason default value of Page_Load() is shown after render.
You have to use the following condition in the Page_Load event handler, not in the Load_Form:
if (!IsPostBack) {
TextBox1.Text = "Hello";
}
Your button click event handler is ok.
Hope it helps!
Please see below code :
Default.aspx:
<asp:TextBox ID="text1" runat="server"></asp:TextBox>
<asp:Button ID="btn" runat="server" OnClick="btn_Click" />
Make sure aspx page contain same code for button as shown above.

How to show the Current date in textBox using Asp.net

Can any one tell me how can I print the current data in this format (dd-mm-yyyy) ?
I am using this command, but it is not working:
protected void TextBoxStartDate_TextChanged(object sender, EventArgs e)
{
TextBoxStartDate.Text = DateTime.Now.ToString();
// TextBoxStartDate.Text = DateTime.Now();
}
I want autofill textbox with a current date
how can i print the current data in this format (dd-mm-yyyy)
Lower mm means minutes..!!
You can use this format:
DateTime.Now.ToString("dd-MM-yyyy");
Change your code like this:
protected void TextBoxStartDate_TextChanged(object sender, EventArgs e)
{
TextBoxStartDate.Text = DateTime.Now.ToString("dd-MM-yyyy");
// TextBoxStartDate.Text = DateTime.Now();
}
Put this TextBoxStartDate.Text = DateTime.Now.ToString(); on PageLoad
protected void Page_Load(object sender, System.EventArgs e)
{
TextBoxStartDate.Text = DateTime.Now.ToString();
}
here is my ASP.cs code:
<asp:TextBox ID="TextBoxStartDate" runat="server" ontextchanged="TextBoxStartDate_TextChanged" Width="150px" Height="16px" ></asp:TextBox>
You can do it on you page Load event.
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Text = System.DateTime.Now.ToShortDateString();
}
You can write it on Page_Load event to get the Current Date Time
The Code will be:-
You must also have namespace included in your code,
aspx and cs:-
<asp:TextBox ID="TextBoxStartDate" runat="server" OnTextChanged="TextBoxStartDate_TextChanged" Width="150px" Height="16px" ></asp:TextBox>
protected void Page_Load(object sender, EventArgs e)
{
TextBoxStartDate.Text = DateTime.Now.ToString();
}
Also as per your code, you need to add onTextChanged event in your code-behind
protected void TextBoxStartDate_TextChanged(object sender, EventArgs e)
{
//do something here
}
UPDATE
You will get something like below in your textbox when you load your page

ASP.NET C# use session data from dropdown

OK so i am a bit lost and could do with some help.
I am creating a program that a user inputs data into a form on the default page (I have that working).
Then i use session variables to get the data input from a text box on the default page and place that data into a drop down menu on Page2 (I have that working).
What im trying to do now is use the data selected from the drop down on the page2 and output it on to a label. any help would be appreciated.
Page2 code bellow session that populates drop down
public partial class About : Page
{
protected void Page_Load(object sender, EventArgs e)
{
MyFruit = Session["Fruitname"] as List<string>;
//Create new, if null
if (MyFruit == null)
MyFruit = new List<string>();
DropDownList1.DataSource = MyFruit;
DropDownList1.DataBind();
}
You can use SelectedIndexChanged event of DropDownList to handle this.
your AutoPostBack property of DropDownBox should be set to True
sample code as below:
Design code: page.aspx
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem>name1</asp:ListItem>
<asp:ListItem>name2</asp:ListItem>
</asp:DropDownList>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
CodeBehind File: page.aspx.cs
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Label1.Text = DropDownList1.SelectedValue.ToString();
}
Not sure if this is what you are looking for but what I am guessing is you want an event for your drop down list to get the info and place it into a session to pass onto the next page
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string item=DropDownList.SelectedItem;
Session["selectedItem"]=item;
Response.Redirect("TheNextPageURL")
}
public partial class TheNextPage : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(Session["selectedItem"]!=null)
{
Label1.Text=Session["selectedItem"].toString();
}
}
}
Hope that helps

onclick second click

New to asp.net, I am having a problem on a website I am creating, I am using a master page to build my pages. I am trying to change the css class of a li tag using the onclick event in linkbuttons:
<asp:LinkButton runat="server" id="AboutButton" OnClick="about_click" PostBackUrl="about.aspx"><span>About</span></asp:LinkButton>
This linkbutton calls a function in the master page's code behind:
protected void about_click(object sender, EventArgs e)
{
if(Page.IsPostBack)
{
about.Attributes.Add`enter code here`("class", "current");
}
}
This only works when the page is loaded and the button is clicked again. Any help would be greatly appreciated.
By adding: if(Page.IsPostBack) you're specifically telling it not to execute that code the first time the page is loaded, but you want it to happen when the page is first loaded, by the sounds of the question.
Why did you add if(Page.IsPostBack). Try this
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
about.Attributes.Add("class", "current"); //initial setting here
}
}
protected void about_click(object sender, EventArgs e)
{
about.Attributes.Add("class", "current");
}

Button.OnClientClick question

I'm gonna post some more code to show exactly what I'm trying to do,
I'm adding the button using programming code and not markup but the OnClick won't work (giving the following error:
System.Web.UI.WebControls.Button.OnClick(System.EventArgs)' is inaccessible due to its protection level.
Button btnopslaan = new Button();
btnopslaan.Text = "Opslaan";
btnopslaan.ID = "btnOpslaan";
btnopslaan.CssClass = ".opslaan";
btnopslaan.Click += new EventHandler(btnopslaanClick);
btnopslaan_arr[btn_count] = btnopslaan;
add_button(btnopslaan);
protected void btnopslaanClick(object sender, EventArgs e)
{
Debug.WriteLine("success");
}
I just can't find out why this isn't working.
Anyone who can help me out?
You need to use OnClick for server side clicks rather than OnClientClick
Either you can use it inline >
<asp:Button id="btnopslaan" runat="server' OnClick="btnopslaanClick" />
Or in Code behind >
btnopslaan.Click+=new EventHandler(btnopslaanClick);
or you make it a postback call to the server. in your
aspx write:
<asp:Button runat="server" ID="buttonOpslaan" Text="opslaan" ></asp:Button>
codebehind write this:
protected void Page_Init(object sender, EventArgs e)
{
buttonOpslaan.Click += new EventHandler(buttonOpslaan_Click);
}
// mind: this method can be private
void buttonOpslaan_Click(object sender, EventArgs e)
{
//do something
}
or handle it with the AutoEventWireUp (recommended) like:
<asp:Button runat="server"
ID="buttonOpslaan"
OnClick="buttonOpslaan_Click"
Text="opslaan" ></asp:Button>
// mind: this method cannot be private, but has to be protected at least.
protected void buttonOpslaan_Click(object sender, EventArgs e)
{
//do something
}
or do it completely from code behind:
// note: buttonOpslaan must have an (autoassigned) ID.
protected void Page_Init(object sender, EventArgs e)
{
Button buttonOpslaan = new Button();
buttonOpslaan.Text = "opslaan!";
buttonOpslaan.Click += new EventHandler(buttonOpslaan_Click);
form1.Controls.Add(buttonOpslaan);
}
protected void buttonOpslaan_Click(object sender, EventArgs e)
{
//do something
}
or handle it clientside with javascript in your ASPX (it will not reach the server)
<script type="text/javascript">
function buttonOpslaan_Click(){
alert("test");
return false;
}
</script>
<asp:Button runat="server"
ID="buttonOpslaan"
OnClientClick="buttonOpslaan_Click()"
Text="opslaan" ></asp:Button>
Update: (by comments)
if you add the control via an eventhandler (like the onchange event of a dropdownlist), the control is 'lost' on next postback, or even as soon as the Page is send to the client (due to the stateless (there is no mechanism to maintain the state of application) behaviour and lifecycle of .Net).
So simply adding a control once is never going to work.
That means you have to rebuild the control every time a postback occurs. My preferred way to do this is store a list/document somewhere that descrbes what controls must be created each time. Possible locations are, from worse to good (IMHO):
Session
Viewstate
Cache
XML/IO
Database
After all, you are posting "data" to the server (that represents a control) and you want to save that for further use.
If the controls to be created aren't that complex you could implement a Factory Pattern like a WebControlFactory that stores only a few properties in a List or Dictionary, which is read every time to recreate the controls again (and again, and again, and again)
btnopslaanClick should be client side, in the .aspx itself have:
<script type="text/javascript">
function btnopslaanClick() {
alert("success");
}
</script>
btnopslaan.Click+=new EventHandler(btnopslaanClick);
protected void btnopslaanClick(object sender, EventArgs e)
{
Debug.WriteLine("succes");
}

Categories