ASP.net How can I invalidate in textchanged event - c#

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;
}

Related

Textbox TextChange event only firing if user hits space button

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"/>

asp:LinkButton, how to cancel OnClick event?

I have searched for hours, but I am lost.
Is there any way to Cancel a OnClick() event from an asp:LinkButton command?
I have the following client side code:
<asp:LinkButton ID="LinkButton3" runat="server" CausesValidation="False" CommandName="Delete" OnInit="SetVisibility" OnClientClick="return confirm('Are you sure?');" Text="Delete" OnClick="LinkButton3_Click"></asp:LinkButton>
The server side code for the OnClick() event is thus ...
//Trap the delete button
protected void LinkButton3_Click(object sender, EventArgs e)
{
try
{
if (ListBox1.SelectedItem.Text == "** NO SCHOOL RECORDED **")
throw new Exception("You cannot delete this entry, as it's the default for every student until a School is selected in Basic Enrolments.");
}
catch (Exception exc)
{
webMessageBox.Show(exc.Message);
return;
}
}
As you can see I want to abort the Delete command if the dropdown in my code has a specific Text.
The Return; statement does nothing. The record still gets deleted!
Is there a way to abort this event, since there is no e.Cancel method?
I've read [this][1] and [this][2], to no avail. The suggestion that there is no way to cancel this event, makes me think that perhaps I should be aborting the delete in the databinding events? Or even better, how to hide the Delete linkbutton if the user selects the above dropdown text?
Thanks in advance.
Thanks
Instead doing it on server side you can do it on client side. You can use require filed validator and use that.
Examples
How to place a required field validator inside a GridView TextBox
How to add a RequiredFieldValidator to DropDownList control?
Or create a javascript or jQuery function on client click and check the dropdown value and do the validation.
UPDATE
I've decided to ditch the OnClick() event entirely and trap the condition using the DetailView's DataBound event. I then checked the value from the dropdownlist and simply hide/show the LinkButton controls as necessary.
ie:
protected void DetailsView1_DataBound(object sender, EventArgs e)
{
LinkButton lnk1 = (LinkButton)DetailsView1.FindControl("LinkButton1");
LinkButton lnk2 = (LinkButton)DetailsView1.FindControl("LinkButton2");
LinkButton lnk3 = (LinkButton)DetailsView1.FindControl("LinkButton3");
if (ListBox1.SelectedItem.Text == "** NO SCHOOL RECORDED **")
{
if (lnk1 != null) lnk1.Visible = false;
if (lnk2 != null) lnk2.Visible = false;
if (lnk3 != null) lnk3.Visible = false;
}
else
{
if (lnk1 != null) lnk1.Visible = true;
if (lnk2 != null) lnk2.Visible = true;
if (lnk3 != null) lnk3.Visible = true;
}
}

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
}

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?

Programatically created events in RowDataBound not firing

I have a GridView which is populated from a database, and includes a textbox. Through the code behind, I want to subscribe the textbox on each row to a certain event, but only if a field of the row matches some if statement.
So I have the following:
protected void grdRates_RowDataBound(object sender, GridViewRowEventArgs e)
{
TextBox txt = (TextBox)e.Row.FindControl("txtValue");
DataRowView dataView = (DataRowView)e.Row.DataItem;
if ((bool)dataView["isAuto"])
{
txt.AutoPostBack = true;
txt.TextChanged += new EventHandler(txt_TextChanged);
}
}
protected void txt_TextChanged(object sender, EventArgs e)
{
//Other stuff here
}
The problem is, the text changed event never fires - the AutoPostBack property is being set, as the page posts back when they move out of the TextBox, but the text changed event does not fire. Am I missing something here?
You should change the implementation so that you are not adding an event handler at the time of data binding, which will get you in all sorts of problems with the page lifecycle.
Instead, you could bind the AutoPostBack property declaratively and just set the event handler there as well.
<asp:TextBox ID="SomeInput" runat="server" ...
AutoPostBack='<%# (bool)Eval("IsAuto")'
OnTextChanged="SomeInput_TextChanged" />
The event will only fire automatically (i.e. when the input loses focus) when IsAuto == true, but it may still fire when the user clicks another button in the same row and the text in the input was changed. So you need an extra check in the event handler:
protected void SomeInput_TextChanged(object sender, EventArgs e)
{
TextBox input = (TextBox)sender;
if(input.AutoPostBack)
{
// Other stuff here
}
}
Notice that by declaratively binding we need to worry less about page life cycle, and we can use the bound property of the input to check against in the event handler.

Categories

Resources