Textbox TextChange event only firing if user hits space button - c#

I only have one textbox on the page. For this textbox I have a textbox text change event in the code behind. Since this is the only element on the page, it's only firing after user enters input and user hits space button. Is there a hack I could use to make textbook tex changed event happen once it looses focus instead of user hitting space button?
<asp:Textbox Id="txtInputID" runat="server" TextChanged="ReadWriteTB_TextChanged" />
private void ReadWriteTB_TextChanged(object sender, RoutedEventArgs e)
{
//do stuff here
}
Update - I use jquery auto complete for this textbox. Not sure if that is causing user to hit space button.

Try this:
private void ReadWriteTB_TextChanged(object sender, RoutedEventArgs e)
{
txtInputID.Attributes.Add("onfocus", "javascript:this.value=this.value;")
txtInputID.Focus()
}
<script type="text/javascript">
var MIN_TEXTLENGTH = 3;
function forcePostback(ctrl) {
if (ctrl != null && ctrl.value && ctrl.value.length >= MIN_TEXTLENGTH) {
__doPostBack(ctrl.id, '');
}
}
</script>
...
<asp:TextBox ID="txtInputID" OnKeyUp="forcePostback(this);" AutoPostBack="true"
OnTextChanged="ReadWriteTB_TextChanged" runat="server"/>

Related

ASP.net How can I invalidate in textchanged event

How can I invalidate the page in textchanged event.
I have a simple form with textboxes and a button to submit
I would like to disable the button or stop the submission if the text entered is not valid.
the validity is to be checked in the textchanged event since I have some db operation to check the validity of the content.
If I can somehow invalidate the page in the textchanged event then it might be easier
pls give me some easy way to implement this
thanks
Shomaail
I was able to resolve my own problem perfectly. I used the customvalidator OnServerValidate Event
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator.onservervalidate(v=vs.110).aspx
Now in my TextChanged event I show up a warning if the data entered is not correct and in the button_click event of my submit button I call Page.Validate() that subsequently calls OnServerValidate event handler of each custom validator associated with a text box.
protected void btnIssueItem_Click(object sender, EventArgs e)
{
Page.Validate();
if (!Page.IsValid)
return;
....
}
protected void tbRoomID_CustomValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
BAL bal = new BAL();
args.IsValid = bal.GetRoomByRoomID(Int32.Parse(args.Value)).Count == 0 ? false : true;
}
You can set Button Enabled Property to true of false, ie:
<asp:TextBox runat="server" ID="txtData" OnTextChanged="txtData_TextChanged"
AutoPostBack="true"></asp:TextBox>
<asp:Button runat="server" ID="btnSave" OnClik="btnSave_Click"></asp:Button>
On Code Behid:
protected void txtData_TextChanged(object sender, EventArgs e)
{
if(txtData.Text == "something")
{
btnSave.Enabled = True;
}
else
btnSave.Enabled = False;
}

Client Interaction in WebForms

What way is standard/ recommended to do the following:
When a user raises the Page_Command "Save" or "Send," I want to run a method. If the method returns false, I want to send the user back to the page and display a message.
All of the data they entered in the form should still be there. The message would have a button that reads, "Send Anyway/ Regardless." If they click it, it will send.
I know I could do this via a webservice and jQuery, but I am asking how I would do this via WebForms.
Here is my basic code:
protected void Page_Command(Object sender, CommandEventArgs e)
{
if ( e.CommandName == "Save" || e.CommandName == "Send" )
{
// run method
}
}
There are several ways you could do this.
One option might be to a button with the text "Save", and another with the text "Send anyway". Make the second button invisible to begin with, and the first visible.
When the first button is clicked, it should run the validation-logic. If validation succeeds, submit - otherwise, hide the first button, and set the other one to visible.
When / if the second button is clicked, the submit is performed without validation.
Update:
With some minor modifications, you should be able to do something like this:
Markup:
<asp:Button runat="server"
ID="myFirstButton"
OnClick="SubmitWithValidation" />
<asp:Button runat="server"
ID="mySecondButton"
Visible="False"
OnClick="SubmitData" />
Code:
protected void SubmitWithValidation(object sender, EventArgs e)
{
if (ValidateMyData())
{
SubmitData(sender, e);
}
else
{
mySecondButton.Visible = true;
myFirstButton.Visible = false;
}
}
private bool ValidateMyData()
{
// Validate stuff
return isValid;
}
private void SubmitData(object sender, EventArgs eventArgs)
{
// Logic to submit your data here
}

C# / asp.net global Variables?

I have two buttons with on click functions
The 1st one gets assigned a variable when Clicked.
How do I get my second button to get the variable from the 1st button when I click button 2?
It doesn't seem to work. As the second button doesn't recognise the Variable.
Thanks
EDIT:
Just to clarify My code is generating a pdf. button 1 selects the url of the template to use. and in button 2 (the one generating the pdf) I want it to get the variable set from button 1 so it knows what template to use.
EDIT 2:
My code does work but only when I'm not using the ajax update panel. it seems that the variable I'm trying to set doesn't get set with AJAX
Your Button have Id, you get this button with his Id
Nota : You can add runat="server" in order to visualize in server side
<asp:Button id="Button1"
Text="Click "
OnClick="Btn1_Click"
runat="server"/>
<asp:Button id="Button2"
Text="Click "
OnClick="Btn2_Click"
runat="server"/>
void Btn2_Click(Object sender, EventArgs e)
{
Button1.Text = "test after click on button 2";
Template = ...;//Set your value
}
void Btn1_Click(Object sender, EventArgs e)
{
Button2.Text = "test after click on button 1";
//Here you can get your value after post.
var result = Template;
}
It's not subject but in delegate you can also get objet button by passing on sender argument.
var button = sender as Button; //You get button who raise event
In order to manage Template Path property.
public string Template
{
get
{
if(ViewState["Template"] != null)
{
return (string)ViewState["Template"];
}
}
set{ViewState["Template"] = value;}
}
i guess you are looking at accessing value of a variable inside the click event of button2 for which the value is set in the button1 click event ?
private string myPrivateString = "";
void Page_Load()//Not sure of correct method signature
{
if(Page.IsPostBack)
{
myPrivateString = Session["myPrivateString"];
}
}
void Button1_Click(object sender, EventArgs e)
{
//There will a postback before this gets executed
myPrivateString = "Value Set From Button 1";
Session["myPrivateString"] = myPrivateString;
}
void Button2_Click(object sender, EventArgs e)
{
//There will a postback before this gets executed
//Accessing myPrivateString here without setting value from session
//will return empty string as after PostBack its a new page thats rendered.
myPrivateString = Session["myPrivateString"]; // Or do it in the Page_Load event
}
I guess now you can get the value of inside the button2 click event.
Also read about ASP.NET Page lifecycle and how client side events like button clicks are handled by the ASP.NET framework.

Dynamically add event to custom control (Confirm Message Box)

I have created a custom cofirm message box control and I created an event like this-
[Category("Action")]
[Description("Raised when the user clicks the button(ok)")]
public event EventHandler Submit;
protected virtual void OnSubmit(EventArgs e) {
if (Submit != null)
Submit(this, e);
}
The Event OnSubmit occurs when user click the OK button on the Confrim Box.
void IPostBackEventHandler.RaisePostBackEvent(string eventArgument)
{
OnSubmit(e);
}
Now I am adding this OnSubmit Event Dynamically like this-
In aspx-
<my:ConfirmMessageBox ID="cfmTest" runat="server" ></my:ConfirmMessageBox>
<asp:Button ID="btnCallMsg" runat="server" onclick="btnCallMsg_Click" />
<asp:TextBox ID="txtResult" runat="server" ></asp:TextBox>
In cs-
protected void btnCallMsg_Click(object sender, EventArgs e)
{
cfmTest.Submit += cfmTest_Submit;//Dynamically Add Event
cfmTest.ShowConfirm("Are you sure to Save Data?"); //Show Confirm Message using Custom Control Message Box
}
protected void cfmTest_Submit(object sender, EventArgs e)
{
//..Some Code..
//..
txtResult.Text = "User Confirmed";//I set the text to "User Confrimed" but it's not displayed
txtResult.Focus();//I focus the textbox but I got Error
}
The Error I got is-
System.InvalidOperationException was unhandled by user code
Message="SetFocus can only be called before and during PreRender."
Source="System.Web"
So, when I dynamically add and fire custom control's event, there is an error in Web Control.
If I add event in aspx file like this,
<my:ConfirmMessageBox ID="cfmTest" runat="server" OnSubmit="cfmTest_Submit"></my:ConfirmMessageBox>
There is no error and work fine.
Can anybody help me to add event dynamically to custom control?
Thanks.
The problem is not with the combination of the event being added late in the life cycle, and what you are trying to achieve with event handler.
As the error clearly states, the problem is with this line:
txtResult.Focus();
If you want to be able to set focus to controls, you must add your event handler on Init or Load.
You can work around this problem by setting the focus at client side using jquery.
var script = "$('#"+txtResult.ClientID+"').focus();";
You would have to emit this using RegisterClientScriptBlock.
The simplest change would be to move the focus() call:
bool focusResults = false;
protected void cfmTest_Sumit(object sender, EventArgs e)
{
txtResult.Text = "User Confirmed";
focusResults = true;
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if(focusResults)
txtResult.Focus();
}
Are you sure txtResult.Text isn't being set again somewhere else?

Get the value of runtime added controls

HTML
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:Button runat="server" ID="show" OnClick="show_Click" Text="show"/>
<asp:Button runat="server" ID="add" OnClick="add_Click" Text="add new "/>
<div id="content" runat="server"></div>
</asp:Content>
code
protected void show_Click(object sender, EventArgs e)
{
Response.Write(((CheckBox) content.FindControl("chb")).Checked);
}
protected void add_Click(object sender, EventArgs e)
{
CheckBox chb = new CheckBox();
chb.ID = "chb";
chb.Text = "chb";
content.Controls.Add(chb);
}
by button add added a new checkbox on runtime.
then i want get checkbox chb by button show
but ((CheckBox) content.FindControl("chb")).Checked return Null.
i want add checkbox dynamically and then checked that which of them checked is true.
This happens because dynamically added controls are not preserved after postbacks. You can easily demonstrate this by adding another button (without a click event handler) to the page. Run the application and click the "add" button to create the checkbox, then click the newly added button and the checkbox will be gone after the postback.
Well, I can not understand what you are trying to achieve but;
protected void show_Click(object sender, EventArgs e)
{
Response.Write((Session["chb"] as CheckBox).Text);
}
protected void add_Click(object sender, EventArgs e)
{
CheckBox chb = new CheckBox();
chb.ID = "chb";
chb.Text = "chb";
content.Controls.Add(chb);
Session["chb"] = chb;
}
Your events don't happen in the same postback of your page - when you click add, it adds the checkbox but then the page execution finishes, the page is sent to the client and it's done with handling that Click event.
When you then click the show button, it's another postback, in which your checkbox has not been created, so it doesn't exist.
To handle this, you have a few options:
1.
Add the checkbox to the page in the designer and set its Visible property to false inially. You can keep the add button, but it won't actually add a checkbox to the page, it'll just make it visible by setting Visible to true.
2.
If you really want to dynamically add the checkbox, then you need to add it every time the page is executed, in one of the page event handlers (for example Load). The way to do that is to save a value in the viewstate or in a hidden field when you click add and based on the value, you'd create the checkbox on subsequent postbacks.
protected void Page_Load (object sender, EventArgs e)
{
if ( IsPostBack )
{
if ( Session["chb"] != null )
CreateChb ();
}
}
protected void show_Click(object sender, EventArgs e)
{
Response.Write(((CheckBox) content.FindControl("chb")).Text);
}
protected void add_Click(object sender, EventArgs e)
{
Session["chk"] = true;
CreateChb ();
}
private void CreateChb ()
{
CheckBox chb = new CheckBox();
chb.ID = "chb";
chb.Text = "chb";
content.Controls.Add(chb);
}

Categories

Resources