Save textbox1.text to a variable on button click asp.net - c#

<asp:TextBox ID="TextBox2" AutoPostBack="true" runat="server" Width="415px" Height="50px" OnTextChanged="TextBox2_TextChanged"></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Save Changes" />
I'm attempting to save the data as such:
protected void TextBox2_TextChanged(object sender, EventArgs e)
{
Session["data"] = TextBox2.Text;
}
And retrieving:
protected void Button1_Click(object sender, EventArgs e)
{
string temp = (string)Session["data"];
}
When i print the string though, I am receiving a white space. Any help would be appreciated. Thanks in advance

In order to store data in Sesstion try something like:
protected void TextBox2_TextChanged(object sender, EventArgs e)
{
Session.Add("data", TextBox2.Text);
}
And no other changes in the retriving part.
As a usage I noticed that when focus is set to text box, the typing cursor is active in text box, the break point in the button's event handler is not hit when pressing the button, so this might be your non functional case.
To get this working after you finish typing into the text box, hit for instance the TAB key and then click on the button and the value from text box is retrived in button's click event handler.

Related

CustomValidator firing but not not preventing postback in ASP.NET

I am using a CustomValidator in ASP.NET as follows.
<asp:CustomValidator ID="AnswerCV" runat="server" ForeColor="Red"
ValidateEmptyText="True" ValidationGroup="test"
OnServerValidate="CustomValidation" ControlToValidate="TextBox1" Enabled="True"
ErrorMessage="You must fill in the text box.">
</asp:CustomValidator>
<asp:TextBox ID="TextBox1" ValidationGroup="test" runat="server">
</asp:TextBox>
<asp:Button runat="server" Id="Button" CausesValidation="True" ValidationGroup="test"
OnClick="Button_Click" />
In the code behind I have
protected void CustomValidation(object sender, ServerValidateEventArgs e)
{
MessageBox.Show("It is firing!!!");
if (string.IsNullOrEmpty(TextBox1.Text))
{
e.IsValid = false;
}
else
{
e.IsValid = true;
}
}
And the button click method is as follows
protected void Button_Click(object sender, EventArgs e)
{
MessageBox.Show("I should not have fired.");
}
The CustomValidation method fires but the Button_Click method fires after that and then the "You must fill in the text box." error message displays. How do I prevent the Button_Click method from firing, when the text box is empty the validation is failing and triggering the error message, but after the Button_click method has fired?
The stackoverflow page here offered other solutions which I have implemented but still the Button_Click method fires.
Aside: And the client side solutions I can not use as I am dynamically going to add code in the Init() method that enables and disables the CustomValidator via a CheckedChanged event in only certain Radio Buttons. End Of Aside
I have also tried the CustomValidator without the OnServerValidate method and I have tried returning a boolean of false from the CustomValidation method cause a syntax error.
protected void Button_Click(object sender, EventArgs e)
{
if (IsValid)
{
Response.Write(" alert ('I should not have fired'); ");
}
}
Please add one if condition in Button_Click Event
protected void Button_Click(object sender, EventArgs e)
{
if (IsValid)
{
Response.Write("<script> alert ('I should not have fired');
</script>");
}
}

Get text/value from textbox after value/text changed server side

I have a FormView with data(DataSource,DataBind) that I fill with value='<%# Eval("Name") %>' , but after I'm changing the text in TextBox and press update button I see the same value that before, I cant see new value that I have typed.
What I am missing here?
my html
<asp:FormView ID="MainFormTemplate" runat="server">
<ItemTemplate>
<li class="li_result" runat="server">
<div class="col-3">
<input id="txt_Name" runat="server" value='<%# Eval("Name") %>'>
</div>
</li>
</ItemTemplate>
</asp:FormView>
<asp:Button id="btn_Update" runat="server" OnClick="btn_Update_Click" Text="Update" />
Server side
protected void Page_Load(object sender, EventArgs e)
{
using (DB_MikaDataContext data = new DB_MikaDataContext())
{
MainFormTemplate.DataSource = data.File_Projects.Where(x => x.Num_Tik.Equals("12")).ToList();
MainFormTemplate.DataBind();
}
}
public void btn_Update_Click(object sender, EventArgs e)
{
//using System.Web.UI.HtmlControls
HtmlInputText twt = (HtmlInputText)MainFormTemplate.FindControl("txt_Name");
string text = twt.Value;//i see old value ,not new one that i typed in text box
}
In every postback, you are always getting the old value from your database. The solution is check if the page is being rendered for the first time (!IsPostBack) then set your MainFormTemplate's DataSource else if is being loaded in response to a postback (IsPostBack) get the txt_Name's value like this:
HtmlInputText twt;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
using (DB_MikaDataContext data = new DB_MikaDataContext())
{
MainFormTemplate.DataSource = data.File_Projects.Where(x => x.Num_Tik.Equals("12")).ToList();
MainFormTemplate.DataBind();
}
}
else
{
twt = MainFormTemplate.FindControl("txt_Name") as HtmlInputText;
}
}
protected void btn_Update_OnClick(object sender, EventArgs e)
{
string text = twt.Value; // You will get the new value
}
with Page_Load executing every postback, you are always writing value from database (?), and value sent from browser is lost (although still exist in Page.Request.Form member).
In ASP.NET, When a page is submitted, the Page_Load event runs before the button click event. So, the textbox value gets repopulated with its original value before the click event looks at that value.
If this is the situation, then you can wrap the code that assigns the value to the textbox in an if block like this:
if (!IsPostBack)
{
HtmlInputText twt = (HtmlInputText)MainFormTemplate.FindControl("txt_Name");
string text = twt.Value;
}
Hope this helps you.

How to force enable/disable of controls in aspx?

I have a simple windows form app which I have to migrate to run on a webpage, so I'm trying with aspx(c#).
I have two radio buttons, but at time only one of them should be checked. I implemented the very same code from the original app, but it's not working:
protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton1.Checked == true)
{
RadioButton2.Checked = false;
}
}
protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton2.Checked == true)
{
RadioButton1.Checked = false;
}
}
So why these changes not being applied on the page?
you can use GroupName Property of RadioButton Control.
if you set the same GroupName for set of RadioButtons you don't need to write the Code Behid which you have written in the above Post/Question, as only one radio button can be selected from the group.
but if you want to invoke some action like Disabling TextBox on Particular Radio Button click event you can use following sample code.
Example: in this example i'm taking 3 Radio Buttons all set to Same GroupName, hence only one RadioButton canbe selected at a time.
when user selects/checks a RadioButton1 i'm Disabling the TextBox1.
Note : Please Make sure that your RadioButton AutoPostBack Property set to True otherwise events on RadioButton won't be fired.
Design Code:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RadioButton ID="RadioButton1" runat="server" Text="DisableTextBox" GroupName="Group1" AutoPostBack="True" OnCheckedChanged="RadioButton1_CheckedChanged"/>
<asp:RadioButton ID="RadioButton2" runat="server" GroupName="Group1" AutoPostBack="True"/>
<asp:RadioButton ID="RadioButton3" runat="server" GroupName="Group1" AutoPostBack="True" />
Code Behind:
protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton1.Checked)
TextBox3.Enabled = false;
else
TextBox3.Enabled = true;
}
Put the checkboxes in a GroubBox or Panel
You can set the GroupName of both radiobuttons the same, so the Code Behind you wrote is not needed anymore.
Also, check out the RadioButtonList
UPDATE
Your aspx-code should look something like this:
<asp:RadioButton id="RadioButtonEnabled" runat="server" Text="Enabled" GroupName="GroupTxtEnabled" AutoPostBack="True" OnCheckedChanged="RadioButtonEnabled_CheckedChanged"/>
<asp:RadioButton id="RadioButtonDisabled" runat="server" Text="Disabled" GroupName="GroupTxtEnabled" AutoPostBack="True"/>
<asp:TextBox id="TextBox1" runat="server"/>
And in your code-behind:
protected void RadioButtonEnabled_CheckedChanged (object sender, EventArgs e)
{
TextBox1 = RadioButtonEnabled.Checked
}
As you can see, I've used the OnCheckedChanged only at one radiobutton, since both radiobuttons are changed at the same time (property GroupName is equal).

Autopostback prevents button click

I have an asp.net page and on it there are a number of controls, including:
A textbox with autopostback = true and the server side textchanged event implemented
A button with the server side click event implemented
The textbox performs the postback as soon as the user leaves the control (ie, focus is lost). The problem is that if the user happens to change the value and then press the button without leaving the textbox, then on button click the textbox will perform the postback but the button click will be lost.
How can i force both the textbox and the button events to fire consecutively in such cases?
Thanks
Try:
ASPX:
<asp:TextBox ID="TextBox1" clientidmode="Static" runat="server" onkeypress="return EnterEvent(event)"></asp:TextBox>
<asp:Button ID="Button1" runat="server" style="display:none" Text="Button" />
JS:
function EnterEvent(e) {
if (e.keyCode == 13) {
__doPostBack('<%=Button1.UniqueId%>', "");
}
}
CS:
protected void Button1_Click1(object sender, EventArgs e)
{
}
You can delay postback from textbox and cancel it in case of button click. To do this add code below to Page_PreRender method:
protected void Page_PreRender(object sender, EventArgs e)
{
Button1.OnClientClick = string.Format("if(window.{0}Timeout){{ clearTimeout(window.{0}Timeout); }}",
TextBox1.ClientID);
TextBox1.Attributes["onChange"] = string.Format("javascript:window.{0}Timeout = setTimeout(\"{1}\", 500); return;",
TextBox1.ClientID,
ClientScript.GetPostBackEventReference(TextBox1, ""));
}

can not read value from dynamically create control

I am stuck with following issue.I've google a lot and try every method but could not solve issue
I am creating control dynamically and after that reading value from dynamically created control
but every time I get error "Object reference is not set to an instance of an object" means I am not able to locate the control even if it available on page.
here is my code
protected void Button1_Click(object sender, EventArgs e)
{
TextBox txt = new TextBox();
txt.ID = "myText";
txt.ViewStateMode = System.Web.UI.ViewStateMode.Enabled;
Panel1.Controls.Add(txt);
}
protected void Button2_Click(object sender, EventArgs e)
{
TextBox txt = Panel1.FindControl("myText") as TextBox;
Response.Write(txt.Text);
}
Here is aspx page code :
<div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<asp:Panel ID="Panel1" runat="server"></asp:Panel>
<asp:Button ID="Button2" runat="server" Text="Button" OnClick="Button2_Click"/>
</div>
That's because you create the control when Button1 is clicked, and then try and access it when Button2 is clicked. Dynamic controls must be created on every post back because that state is not maintained. Instead of just building the control in Button1 click, set a flag in Session so you know to rebuild it on Load too. So, in Button1_Click, at the very end of the method, add this line:
Session["BuildMyText"] = true;
and then in Page_Load:
if (Session["BuildMyText"] != null && (bool)Session["BuildMyText"])
{
// build the text box here too
}
and then finally, wrap the construction of the text box in the Button1_Click like this:
if (Session["BuildMyText"] != null && (bool)Session["BuildMyText"])
{
...
}
You need to recreate the control as below:
protected void Button2_Click(object sender, EventArgs e)
{
TextBox txt = new TextBox(); //add this line
TextBox txt = Panel1.FindControl("myText") as TextBox;
Response.Write(txt.Text);
}

Categories

Resources