C# code behind Required validation - c#

I am writing a c# code for a Required field validator for a Multiline text box.
I have a issue in the run time:
when i won't enter any text inside the
text box
For first Click on submit (Button) it shows the error message
For second Click on submit it won't validate the text box and the form is submitted.
Same two issues when i even enter any
text inside the text box.
Overall it is not validating...
Please help me on what could be the possible bug in the below code.
txtReport = new InputFormTextBox();
txtReport.TextMode = TextBoxMode.MultiLine;
txtReport.RichText = true;
txtReport.RichTextMode = SPRichTextMode.Compatible;
txtReport.Rows = 5;
txtReport.Width = new Unit(200);
txtReport.ID = "txtReport";
txtReport.Text.Trim();
this.Controls.Add(txtReport);
reqVal = new RequiredFieldValidator();
reqVal.ID = "reqVal";
reqVal.ControlToValidate = txtReport.ID;
reqVal.SetFocusOnError = true;
reqVal.ErrorMessage = "*Comments field is mandatory";
reqVal.Enabled = true;
this.Controls.Add(reqVal);
Thanks in advance

From what it sounds like you are not re-adding the validator after the first submit, causing the second submit not to validate. But it's hard to tell from the fragment you posted (in what event/method is this being called?).

Related

Dynamic ModalPopupExtender not firing the OK Click event

ASP.NET 4.7.2 Web Forms c# VS 2019
I am trying to use a modalpopupextender to prompt for new data for foreign key fields. Like the form itself, the MPE is built on the fly in code -- in this case the click handler for the hidden button that the Javascript fires off to build and show the MPE.
I read every single article on SO and the ASP forums and tried everything I saw there. No joy. I get the popup perfectly. Hitting OK closes the popup, but never fires the OK Event.
Here is the code:
//Building the form, we do this in OnInit:
// AJAX Update Panel
UpdatePanel PUP = new UpdatePanel()
{
ID = "PUP",
};
PlaceHolder.Controls.Add(PUP);
// HiddenField containing the field name to permit
// creating the correct modalpopup.
HiddenField HFPopupField = new HiddenField()
{
ID = "HF_POPUP"
};
PUP.ContentTemplateContainer.Controls.Add(HFPopupField);
// Create Hidden button to track the popup
Button BPopup = new Button()
{
ID = "BPOPUP",
UseSubmitBehavior = false
};
BPopup.Click += BPopup_Click;
BPopup.Attributes.Add("style", "display: none;");
PUP.ContentTemplateContainer.Controls.Add(BPopup);
// And create the background panel for the popup.
Panel PnlPopup = new Panel()
{
ID = "PNLPOPUP",
CssClass = "MpeBackground"
};
PnlPopup.Attributes.Add("style", "display: none;");
PUP.ContentTemplateContainer.Controls.Add(PnlPopup);
/// Event handler for hidden button.
protected void BPopup_Click(object sender, EventArgs e)
{
[snip -- code to get the dataset that is being filled]
UpdatePanel PUP = Placeholder.FindControlRecursive("PUP");
Table T = new Table()
{
CssClass = "PopupTbl"
};
TableRow TRTitle = new TableRow();
TableCell TCTitle = new TableCell()
{
CssClass = "PopupTitle",
ColumnSpan = 2
};
Label LPopTitle = new Label()
{
Text = [title of the popup]
};
TCTitle.Controls.Add(LPopTitle);
TRTitle.Cells.Add(TCTitle);
DataRow drData = null;
// Add Fields, and also the cancel and Add buttons
foreach (DataColumn DC in dsColumns.Tables[0].Columns)
{
TableRow TRColumn = [create a tablerow with 2 columns, a prompt and the input field]
if (TRColumn != null)
{
T.Rows.Add(TRColumn);
[snip]
}
} // end of foreach(DataColumn DC in dsColumns.Tables[0].Columns)
PnlWindow.Controls.Add(T);
TableRow TRButtons = new TableRow();
TableCell TCButtons = new TableCell()
{
ColumnSpan = 2,
CssClass="PopupButtons"
};
Button MPEBOK = new Button()
{
ID = "MPE" + sFieldName + "_MPEBOK",
Text = "OK",
CausesValidation = false,
UseSubmitBehavior = false
};
MPEBOK.Click += MPEBOK_Clicked;
TCButtons.Controls.Add(MPEBOK);
LiteralControl LCB = new LiteralControl()
{
Text = " "
};
TCButtons.Controls.Add(LCB);
//************************************************************
//*** Postback Trigger ***
//************************************************************
AsyncPostBackTrigger trigger = new AsyncPostBackTrigger()
{
ControlID = MPEBOK.ID,
EventName = "click"
};
PUP.Triggers.Add(trigger);
//************************************************************
//*** Cancel Button ***
//************************************************************
Button MPEBuhBye = new Button()
{
ID = "MPE" + sFieldName + "_BUHBYE",
Text = "Cancel",
UseSubmitBehavior = false
};
TCButtons.Controls.Add(MPEBuhBye);
TRButtons.Cells.Add(TCButtons);
T.Rows.Add(TRButtons);
PnlPopup.Controls.Add(PnlWindow);
AjaxControlToolkit.ModalPopupExtender MPE = new AjaxControlToolkit.ModalPopupExtender()
{
ID = "MPE" + sFieldName,
PopupControlID = "PNLPOPUP",
TargetControlID = "BPOPUP",
BackgroundCssClass = "MpeBackground"
};
// Add the MPE to the UpdatePanel.
PUP.ContentTemplateContainer.Controls.Add(MPE);
// Show the modal popup extender.
MPE.Show();
}
protected void MPEBOK_Clicked(object sender, EventArgs e)
{
[snip - this never fires]
}
I cannot find out what is happening here. Can anyone see something hinky?
Thanks
John.
You can't add a server side button or inject a server side button into the page DOM.
When you drag a asp.net button onto the form, BOTH the "mypage.cs" and mypage.desinger.cs ARE updated. The wire up of the button occurs at design time, and you would have to modify mypage.desinger.cs ALSO and ADD a button event stub.
So you can't do this.
A compromise would be to also add some js and have that HTML button execute a .click() method of a hidden asp.net button you drop into that page (that would give you the post back, and the running behind of a separate button event code stub.
This event resolution occurs at compile time - not at page render time. You have to drop that button onto the page.
I suppose you could adopt a standard that you always place right below that "div" on the page the button (hidden with style=none. And then as noted, have your injected code along with some js execute a click on the hidden button. Or just have the js button code execute a __doPostback("some value") and pick this up in the page on-load event, and then call the routine (function) from on-page load event.
I think better would be to use a jQuery.UI dialog, as that dialog CAN say load + use another different web page into a “div” on the existing page. So you layout, make, and create the nice looking popup form as a separate web page. jQuery is able to remove the “form” and additonal tags out of that page load, and then inject it into the existing page. (that code would be rather hard to re-produce). so jQuery.UI is able to pop up that separate page. however, the buttons on that loaded page (into that div) of course can't really run any code behind in the current page. However, the buttons CAN run local js in the current page. Thus the actions of this injected page would be local to each page. But the popup would not be directly calling a code behind stub.
Now, to adopt jQuery.UI, then you also have to of course adopt jQuery. So that is two extra libraries you need. (but, jQuery you likely already have).
However, I suppose the whole point of using the ajax toolkit is to avoid jQuery.ui in the first place. To be fair, before jQuery.ui came along, that tool kit was REALLY impressive, and gave asp.net folks a REAL leg up on the competition. (and it tends to be MUCH less wiring up then say using jQuery.UI
So the AjaxToolkit in its heyday was impressive. Now, it of course showing its age, but I still use the kit, and this is especially the case for the AjaxFileUploader. And yes I do use the popups – even to this day. However, I find now that jQuery.UI dialogs are more flexible, and would be better in this case (because you want a on-the fly setup).
Also, having code behind buttons in even the jQuery.UI dialog, or in this case the ajax popup? Well, only the action button can run code behind. The cancel button of course will just dismiss the dialog. However, any button in the dialog that WILL run code behind? Well, that's ok, since you have a page post back, and it actually the page postback that BLOWS out the dialog anyway.

The name "locBox does not exist"

I'm using code to create a dynamic text box, including assigning it a name, and then attempting to append new text to the textbox, however I'm receiving an error that the name doesn't exist in the current context.
Am I missing something simple, or have a done something wrong? I apologize if this is a basic thing I'm doing wrong; I'm still learning.
Here's the code in question:
TextBox dynamicTextBox = new TextBox();
dynamicTextBox.Name = "locBox";
dynamicTextBox.Multiline = true;
dynamicTextBox.Width = 300;
dynamicTextBox.Height = 40;
dynamicTextBox.Text = "Text ");
dynamicTextBox.ControlAdded += locBox;
locBox.AppendText = var1.ToString();
locBox.AppendText = var2.ToString();
The locBox is not defined. you have to remove the last two statement. and change the last statement after removal too.
replace "dynamicTextBox" to the form control instance .
{form instance name}.ControlAdded += locBox;
"{}" is a place holder.
I don't know how helpful this is.

coded ui test project, obtain value of asp label

Created a simple calculator app in webforms.
User enters a number in a text field MainContent_numberTb and clicks on results button.
Added a new 'coded UI Test Project' to my solution. Have tested the UI by adding '5', This all works fine. Would now like to compare the actual result against the expected result.
BrowserWindow Browser = BrowserWindow.Launch("http://url");
UITestControl UiInputField = new UITestControl(Browser);
UiInputField.TechnologyName = "Web";
UiInputField.SearchProperties.Add("ControlType", "Edit");
UiInputField.SearchProperties.Add("Id", "MainContent_numberTb");
//Populate input field
Keyboard.SendKeys(UiInputField, "5");
//Results Button
UITestControl ResultsBtn = new UITestControl(Browser);
ResultsBtn.TechnologyName = "Web";
ResultsBtn.SearchProperties.Add("ControlType", "Button");
ResultsBtn.SearchProperties.Add("Id", "MainContent_calBtn");
Mouse.Click(ResultsBtn);
All above code works fine, problem occurs when trying to access the label
<asp:Label ID="AllNumLbl_Res" runat="server"></asp:Label>
What do I insert beside control type? It's not edit as edit is the text field. Then also, what stores the actual result so I can compare AllNumsTB?
string expectedAllNums = "1, 2, 3, 4, 5";
UITestControl AllNumsTB = new UITestControl(Browser);
AllNumsTB.TechnologyName = "Web";
AllNumsTB.SearchProperties.Add("ControlType", "?????");
AllNumsTB.SearchProperties.Add("Id", "MainContent_AllNumLbl_Res");
if(expectedAllNums != AllNumsTB.??????)
{
Assert.Fail("Wrong Answer");
}
UPDATE
OK so using the debugger console I was able to get the value of the label using ((Microsoft.VisualStudio.TestTools.UITesting.HtmlControls.HtmlSpan)new System.Collections.ArrayList.ArrayListDebugView(((System.Collections.CollectionBase)(AllNumsTB.FindMatchingControls()).List).InnerList).Items[0]).DisplayText
but when I use this in the code & ArrayListDebugView are inaccessible due to protection??
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
UPDATE
Thanks K Scandrett for the answer...If I may I was wondering could you also please help me with the validation...If the user enters a letter or a non positive number the error message will fire..
<asp:RegularExpressionValidator ID="regexpName"
//VALIDATION MESSAGE
UITestControl PositiveNumValMsg = new UITestControl(Browser);
PositiveNumValMsg.TechnologyName = "Web";
PositiveNumValMsg.SearchProperties.Add("Id", "MainContent_regexpName");
This all works fine, however I want to test if the label appears or not...so far I have tried
//bool visible = false;
//System.Drawing.Point p;
//// If the control is offscreen, bring it into the viewport
//PositiveNumValMsg.EnsureClickable();
// // Now check the coordinates of the clickable point
// visible = PositiveNumValMsg.TryGetClickablePoint(out p)
// && (p.X > 0 || p.Y > 0);
var isVisible = PositiveNumValMsg.WaitForControlPropertyNotEqual(UITestControl.PropertyNames.State, ControlStates.Invisible);
but they all return true even when the label is not shown, but it is still on the page just set to invisible. In that case I should check its style..something like
//string labelText3 = PositiveNumValMsg.GetProperty("style").ToString();
then check if the style contains visibility: visible?
You want to grab its InnerText property.
It's not mandatory to set ControlType, so some variation of the following should work:
UITestControl AllNumsTB = new UITestControl(Browser);
AllNumsTB.TechnologyName = "Web";
AllNumsTB.SearchProperties.Add(HtmlControl.PropertyNames.Id, "MainContent_AllNumLbl_Res");
var result = AllNumsTB.GetProperty(HtmlLabel.InnerText).Trim();
// var result = AllNumsTB.GetProperty("InnerText").Trim();
OR from https://social.msdn.microsoft.com/Forums/en-US/69ea15e3-dcfa-4d51-bb6e-31e63deb0ace/how-to-read-dynamic-text-from-label-using-coded-ui-for-web-application?forum=vstest:
var AllNumsTB = new HtmlLabel(Browser);
AllNumsTB.TechnologyName = "Web";
AllNumsTB.SearchProperties.Add(HtmlControl.PropertyNames.Id, "MainContent_AllNumLbl_Res");
var result = AllNumsTB.InnerText;
string result2;
// you may need to include this section, or you may not
if (result.Length > 0)
{
AllNumsTB.WaitForControlReady();
result2 = AllNumsTB.InnerText;
}
EDIT: Regarding testing an ASP.Net Validator
I've been able to check whether the validator message is displayed with the following method:
1) Created a test asp.net page with a regex validator that requires exactly 2 digits:
<asp:TextBox ID="numberTb" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="regexpName" ControlToValidate="numberTb" ValidationExpression="\d{2}" runat="server" ErrorMessage="Please enter 2 digits"></asp:RegularExpressionValidator>
<asp:Button ID="Button1" runat="server" Text="Button" />
2) Ran the Coded UI Test builder and started recording =>
Clicked Input box; typed s; hit tab (the validator error message is showing).
3) Paused the Recorder.
4) Clicked "Generate Code" icon and give it a method name; clicked "Add and Generate" button.
5) Now I dragged and dropped the Crosshair icon onto the validator message. Scrolling down the list of options is the ControlDefinition. Right-clicked it and selected "Add Assertion...".
6) Changed the Comparator to "Contains"; the Comparison Value to " visible;"; and gave it an Assertion Failure message.
7) Clicked the "Generate Code" icon, gave it a method name, etc.
Now we have code that will test the validator by running two methods - first to enter the input and trigger (or not) the validator message; the second to test the validator's message visibility. I copied and pasted the generated code and used it to write another opposing test using " hidden;" when given correct input. Ran both tests, and they both passed.
You will end up with something like (have substituted values):
public void DigitValidatorMsgShownWithIncorrectStringInput()
{
#region Variable Declarations
HtmlSpan uIAtleast2digitsPane = this.UIHomePageMyASPNETApplWindow.UIHomePageMyASPNETApplDocument.UIAtleast2digitsPane;
#endregion
// Verify that the 'ControlDefinition' property of 'At least 2 digits' pane contains ' visible;'
StringAssert.Contains(uIAtleast2digitsPane.ControlDefinition, " visible;", "The validator was not shown");
}
Of course all this can be coded manually once you know what you're looking for.

How do i bind an "Entry Cell" to a custom object using Xamarin?

I have been playing with Xamarin for a short time so far, and i just stumbled into something i couldn't find the answer into their documentation.
I am building a fairly simple app that retrieves "User Data" (username, email, password and so forth) from a RESTfull API and populates a listview with some of the data (This is the point i am at the moment. It works).
The next step is to build a "Edit User" screen, which is invoked uppon selecting (tapping) a user on the Listview i currently have.
I have managed to build a simple view that is basically two Entry Cells showing the data of the user picked into the previous listview screen. That also works.
The problem is that, once i edit the data into the "Entry Cell" it has no reflection into the "User Model" that populated the "entry cell" in first place.
How do i bind those together?
Code Sample:
// Entry Cell of Username (Should be Binded)
EntryCell ecUsername = new EntryCell()
{
Label = "Username:",
Placeholder = "username / login",
Text = _user.Username
};
// Entry Cell of Password (Should be Binded)
EntryCell ecEmail = new EntryCell ()
{
Label = "Email:",
Placeholder = "user email",
Text = _user.Email
};
Some Screenshots:
Once i click into a user, its data gets rendered into the next screen.
I haven't tested this, but something like this should work:
EntryCell ec = new EntryCell ();
ec.BindingContext = _user;
ec.SetBinding (EntryCell.TextProperty, "Username");

How to retrieve text from a TextBox that was created programatically

Alright, so I have a form set up that contains a label and a button. When the button is pressed it creates several labels and and two textfields in a specific area.
I cannot for the life of me, figure out how to retrieve the text from those textfields and store it in a public string.
Any help would be wonderful and greatly appreciated.
Edit: As per request.
TextBox playertextbox = new TextBox();
playertextbox.Location = new Point(460, 200);
this.Controls.Add(playertextbox);
You can assign a name to the textbox and later use ControlCollection.Find to retrieve it
Try this
TextBox playertextbox = new TextBox();
playertextbox.Location = new Point(460, 200);
playertextbox.Name = "playertxtBox"; // Add some name
this.Controls.Add(playertextbox);
Then use the name in the button click handler or similar :
//Use that name to search here
TextBox playertextbox = ((TextBox) this.Controls.Find("playertxtBox",true)[0]);
string text = playertextbox.Text;

Categories

Resources