Dynamically Add RegularExpressionValidator C# - c#

I have this FileUpload control that automatically adds a FileUpload Control. But I need to have it also create an RegularExpressionValidator. Not sure how I can do this.
Any ideas?
<script type = "text/javascript">
var counter = 0;
function AddFileUpload() {
var div = document.createElement('DIV');
div.innerHTML = '<input id="file' + counter + '" name = "file' + counter +
'" type="file" />' +
'<input id="Button' + counter + '" type="button" ' +
'value="Remove" onclick = "RemoveFileUpload(this)" />';
document.getElementById("FileUploadContainer").appendChild(div);
counter++;
}
function RemoveFileUpload(div) {
document.getElementById("FileUploadContainer").removeChild(div.parentNode);
}
</script>
<div id="FileUploadContainer">
<asp:FileUpload ID="FileUpload1" runat="server" />
<!--FileUpload Controls will be added here -->
</div>
<br />
<input id="Button1" onclick="AddFileUpload()" style="height: 27px; width: 150px;" tabindex="25" type="button" value="Add More Attachments" />
<asp:RegularExpressionValidator ID="rexp" runat="server" ControlToValidate="FileUpload1"
ErrorMessage="Only .pdf, .jpg"
ValidationExpression="(.*\.([Pp][Dd][Ff])|.*\.([Jj][Pp][Gg])$)">
</asp:RegularExpressionValidator>

Probably you could try this way:
Always initiate Regular Expression Validator in the page along with the control.
Make the Regular Expression Validation disable through javascript and make the control's display to none if you don't need the control
presence in the UI.
Make the Regular Expression Validation enable through javascript and make the control's to be appeared if you need the control presence
in the UI.
Good Reference to read for this:
http://msdn.microsoft.com/en-us/library/aa479045.aspx

Related

How to stop post-back from going back on top of the page?

my concern is about post-back. I have 3 textboxes, the last name, first name and username. I want to combine last name and first name to create a username have lastname.firstname format. My code in .aspx is as follows. The post-back is true for first name because after the user enters the first name, it will automatically generate the username.
<strong>LAST NAME: <span style="color: #FF0000">*</span> </strong>
<asp:TextBox ID="txtLname" runat="server"
Width="197px" onkeypress="return Alphabet()" BorderStyle="Solid"></asp:TextBox>
<strong>FIRST NAME: <span style="color: #FF0000">*</span> </strong> <asp:TextBox ID="txtFname" runat="server" Width="199px"
onkeypress="return Alphabet()" AutoPostBack="True"
ontextchanged="txtFname_TextChanged" BorderStyle="Solid"></asp:TextBox>
<strong>USERNAME: </strong> <asp:TextBox
ID="txtUser" runat="server"
Width="225px" ReadOnly="True" style="margin-left: 6px" BorderStyle="Solid" onkeypress="return Alphabet()"></asp:TextBox>
My code in .aspx.cs is as follows.
protected void txtFname_TextChanged(object sender, EventArgs e)
{
string mystring = txtFname.Text;
mystring = Regex.Replace(mystring, #"\s+", "");
txtUser.Text = txtLname.Text + "." + mystring;
}
this is to trigger the automatic generation of username.
To sum it up, I want to know how to stop post-back from going back to the top of the page after entering the first name for automatic generation of username. thank you very much.
Adjust as you need:
<html>
<head></head>
<body>
<form action="">
Last Name :<input id="txtLastName" name="txtLastName" type="text" oninput="updateUserName()"></input><br />
First Name:<input id="txtFirstName" name="txtLastName" type="text" oninput="updateUserName()"></input><br />
Username:<input id="txtUserName" name="txtLastName" type="text" readonly></input><br />
<button type="submit">Submit</button>
</form>
<script>
function updateUserName()
{
var last_name = document.getElementById("txtLastName").value;
var first_name = document.getElementById("txtFirstName").value;
if(last_name !== "" && first_name !== "")
document.getElementById("txtUserName").value = last_name+"."+first_name;
}
</script>
</body>
</html>

How to prevent the trigger of another button

I have the following in my ASP.net page:
<input type="text" placeholder="Search..." size="30" id="pageLink" />
<br />
<span id="imgGo" class="imgGo floatRight"></span>
JQuery:
$('.imgGo').click(function () {
var strString = $("#pageLink").val()
var strSearch = "http://www.google.com/search=";
var url = strSearch + strString;
window.open(url, '_blank');
return false;
});
$("#pageLink").keyup(function (event) {
if (event.keyCode == 13 || event.which == 13) {
$(".imgGo").click();
}
});
When I enter something in the textbox and click the imgGo span it works fine but if instead I hit enter, my search button which is in another panels gets triggered.
How can I either modify my JQuery code to ensure that doesn't happen or add code-behind to ensure imgGo is triggered only if enter button is pressed while the pageLink textbox has the focus?
I tried the following but didn't work because imgGo is not a button:
<asp:Panel ID="pnlMedSearch" runat="server" DefaultButton="GoImg">
<!--<input type="text" placeholder="Search..." size="30" id="p2" />-->
<asp:TextBox Width="30" ID="pageLink" runat="server" />
<br />
<!--<span id="imgGo" class="imgGo floatRight"></span>-->
<asp:Label ID="imgGo" CssClass="imgGo floatRight" runat="server" />
</asp:Panel>
I get the following error:
The DefaultButton of 'pnlMedSearch' must be the ID of a control of type IButtonControl.
I would like to use the textbox which is not a ASP.net control because the placeholder attribute is important in my case.
I kept the same HTML content and modified my Jquery to the following:
$("#medlineSearch").keypress(function (event) {
if (event.which == 13) {
$("#imgGo").click();
return false;
}
});
Adding the return false; ensure it didn't invoke anything else on the page.
Alternate version for the same.
Register as an event on any tags:
onkeydown="pressButtonOnEnter('IdOfMyButton', event);"
Into your .js file:
function pressButtonOnEnter(buttonId, event) {
var key = (evt.which) ? evt.which : evt.keyCode;
if (key == 13) {
$("#" + buttonId).click();
}
}
It works in asp.net as well.You can simply add it to an asp:textbox for instance.

Dynamic jQuery 'add a textbox' to an asp:Repeater using C#

I'm having problems with a chunk of code that's meant to add a textbox to a Repeater in ASP.
I have the following:
<asp:Repeater ID="uxRolesList" runat="server">
<ItemTemplate>
<div id="<%# GetRolesDivId() %>" class="div_row">
<asp:TextBox ID="uxTxtBoxRole" runat="server" rows="5" columns="100" Text='<%# DataBinder.Eval(Container.DataItem, "RequirementDescription") %>' TextMode="multiline" MaxLength="2000"></asp:TextBox>
<input type="button" style="vertical-align:top;" value="X" class="remove-roles-btn" />
<br /><br />
</div>
</ItemTemplate>
</asp:Repeater>
Which generates a load of textboxes that look like this in the html:
<td id="rolesColumn">
<div id="roles-0" class="div_row">
<textarea name="ctl00$mainContent$uxRolesList$ctl00$uxTxtBoxRole" rows="5" cols="100" id="ctl00_mainContent_uxRolesList_ctl00_uxTxtBoxRole">Cool Job1</textarea>
<input type="button" style="vertical-align:top;" value="X" class="remove-roles-btn" />
<br /><br />
</div>
</td>
I've also added the following button, that should add a textbox to this list when hit:
<asp:Button CssClass="btn" ID="uxAddRoleBtn" runat="server" Text="Add a new role requirement" />
Using the following jQuery code:
$("#ctl00_mainContent_uxAddRoleBtn").live("click", (function (e) {
var rolesCounter = $('#ctl00_mainContent_uxTxtBoxRolesCount').val();
if (rolesCounter < 10) {
var rolesCounterText = "0" + rolesCounter;
} else {
var rolesCounterText = rolesCounter;
}
$('#rolesColumn').append("<div id='roles-" + rolesCounter + "' class='div_row'><textarea name='ctl00$mainContent$uxRolesList$ctl" + rolesCounterText + "$uxTxtBoxRole' rows='5' cols='100' id='ctl00_mainContent_uxRolesList_ctl" + rolesCounterText + "_uxTxtBoxRole' MaxLength='2000' ></textarea><input type='submit' name='ctl00$mainContent$uxRolesList$ctl" + rolesCounterText + "$uxRemoveRoleBtn' value='X' id='ctl00_mainContent_uxRolesList_ctl" + rolesCounterText + "_uxRemoveRoleBtn' class='remove-roles-btn' style='vertical-align:top;' /><br /><span id='ctl00_mainContent_uxRolesList_ctl" + rolesCounterText + "_uxValTxtBoxRole' style='color:Red;visibility:hidden;'>Please complete this role requirement</span><br /><br /></div>");
e.preventDefault();
rolesCounter++;
$('#ctl00_mainContent_uxTxtBoxRolesCount').val(rolesCounter);
}));
So far so good. I hit the add button and the textbox appears, I type something in, everything's great. The html look something like this:
<div id="roles-0" class="div_row">
<textarea id="ctl00_mainContent_uxRolesList_ctl00_uxTxtBoxRole" cols="100" rows="5" name="ctl00$mainContent$uxRolesList$ctl00$uxTxtBoxRole">Cool Job1</textarea><input class="remove-roles-btn" type="button" value="X" style="vertical-align:top;"><br><br>
</div>
<div id="roles-1" class="div_row">
<textarea id="ctl00_mainContent_uxRolesList_ctl01_uxTxtBoxRole" maxlength="2000" cols="100" rows="5" name="ctl00$mainContent$uxRolesList$ctl01$uxTxtBoxRole">Test</textarea><input class="remove-roles-btn" type="submit" style="vertical-align:top;" value="X" name="ctl00$mainContent$uxRolesList$ctl01$uxRemoveRoleBtn"><br><br>
</div>
Then I hit submit and the new values do not come through.
In the C# side I'm trying to access the data using:
foreach (RepeaterItem item in dl.Items)
{
System.Web.UI.WebControls.TextBox rb = item.FindControl(control) as System.Web.UI.WebControls.TextBox;
if (rb.Text.Trim() != "")
{
PositionRequirement pr = new PositionRequirement();
pr.RequirementDescription = rb.Text;
pr.RequirementLevel = new PositionRequirementLevel(level, levelDescription);
pr.OrderNumber = i;
i++;
positionRequirements.Add(pr);
}
}
where dl = uxRolesList
control = uxTxtBoxRole
I'm at an utter loss as to why the new values are not coming through with the uxRolesList Repeater.
What am I doing wrong?
from what i know , the approach used is not going to show the items that are added within the Repeater Datasource, unless they exist before the page is being served to the user, so in the example, only the items that were bound to the repeater before leaving the server (if any) will show.
if you don't want to leave the page and make a trip to the server on every add click,of the top my head i would suggest that you would access them via the request Object using the name instead of the id ( Request[""] ) and keep the name of each textbox similar ("txtbox1","txtbox2")and append the count as you did in your Jquery code, then on the server when the page is submitted loop over the items using the counter that you have stored in uxTxtBoxRolesCount.

Accessing <div> from both javascript and code-behind

I have a div with style="display:none". The div should become visible on pressing an html button:
function JSAdd() {
document.getElementById('divDetail').style.display = "block";
}
<div style="float:left">
<div id="ctl00_MainContent_upnlLbRD">
<select size="4" name="ctl00$MainContent$lbRD" id="ctl00_MainContent_lbRD" style="width:188px;">
<option value="5">one</option>
<option value="1">two</option>
</select>
<input id="btnAdd" type="button" value="Добавить" onclick="JSAdd();" />
<input id="btnEdit" type="button" value="Редактировать" onclick="JSEdit();" />
</div>
<div id="ctl00_MainContent_divDetail" style="display:none" clientidmode="static">
<div id="ctl00_MainContent_upnlDescription">
<div>
<span id="ctl00_MainContent_lblDescription">Описание:</span>
<input name="ctl00$MainContent$txtDescription" type="text" id="ctl00_MainContent_txtDescription" />
<span id="ctl00_MainContent_txtDescriptionRequiredFieldValidator" style="color:Red;visibility:hidden;">Описание является обязательным для заполнения</span>
</div>
<input type="submit" name="ctl00$MainContent$btnSave" value="Сохранить" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$MainContent$btnSave", "", true, "", "", false, false))" id="ctl00_MainContent_btnSave" />
I need to be able to make the div invisible again from code-behind. I cannot access the div unless it is runat="server". But when I add runat="server", the div doesn't become visible on pressing the button from the javascript function above. Could you please help me with this?
Thanks,
David
You can access a div in code-behind by adding the runat="server" attribute. Adding this attribute does change the way you access the element in JavaScript though:
var el = document.getElementById("<%=div1.ClientID%>");
if (el){
el.style.display = "none"; //hidden
}
There are two ways to adjust the visibility from code-behind, but since you're setting display:none in JavaScript, you'd probably want to use the same approach in code-behind:
div1.Style["display"] = "block"; //visible
In code-behind, you can also set the Visible property to false, but this is different because it will prevent the element from being rendered at all.
EDIT
If the div is still showing with display:none present, you probably have an unclosed tag or quote somewhere affecting the markup. Double check and make sure that the markup is valid.
Use a Panel, it renders as a classic div
<asp:Panel runat="server" ID="divDetail" ClientIDMode="Static" />
You have a few options, use ClientIDMode="Static" or use the dynamic ClientID at run-time. Both of these options give you server-side access to the object.
Dynamic:
<div id="divDetail" runat="server" />
//or
<asp:panel id="divDetail" runat="server" />
function JSAdd() {
document.getElementById('<%= divDetail.ClientID %>').style.display = "block";
}
//to hide from code-beind
divDetail.Attributes.Add("style","display:none;");
Static(.NET 4.0 +):
<div id="divDetail" runat="server" ClientIdMode="Static">
//or
<asp:panel id="divDetail" runat="server" ClientIdMode="Static" />
function JSAdd() {
document.getElementById('divDetail').style.display = "block";
}
When runat="server" is applied to an element, asp.net ensures that it has a unique ID by mangling it. Simply ask asp.net for the real client id:
function JSAdd() {
document.getElementById("<%=div1.ClientID%>").style.display = "block";
}
Alternatively, you could tell asp.net to leave your ID alone by adding this to your div:
<div id="div1" runat="server" clientidmode="Static">
Resources:
ClientIdMode="Static" docs
In ASP.NET, to make IDs unique (if multiple control loaded where same ID are specified), ID on elements are often follow a convention like ctl00_container1_container2_controlID and this is what returned when you call control.ClientID.
If you consider such a case where there's same ID on the serverside and you loaded those two controls in your page, you may consider using jQuery and life would be easier with runat="server" with just matching the ID with the end part:
function JSAdd() {
$("div[id$=divDetails]").show();
}
Simplest technique will be to use Javascript/Jquery to Changes Display property of the Div. if not that you can use following code
<form method="post" runat="server">
<div style = "display:none" id= "div1" runat ="server" >Hello I am visible</div>
<asp:Button Text="display Div" runat ="server" ID ="btnDisplay" OnClick = "displayDiv" />
<asp:Button Text="display Div" runat ="server" ID ="btnHideDiv" OnClick = "hideDiv" />
</form>
code behind code is as follows
protected void displayDiv(object sender, EventArgs e)
{
div1.Style.Clear();
div1.Style.Add("display", "block");
}
protected void hideDiv(object sender, EventArgs e)
{
div1.Style.Clear();
div1.Style.Add("display", "none");
}
guess you Got your solution

Write date in asp:TextBox

<asp:TextBox ID="txtDate" runat="server" Value="<%= DateTime.Today.ToShortDateString() %>" />
Value="<%= DateTime.Today.ToShortDateString() %>" does not write date in txt field but whole string. What i am doing wrong?
using JavaScript and jQuery:
var now = new Date();
$('#txtDate').text(now.getDate() + '/' + now.getMonth()+ '/' + now.getYear());
or plain JavaScript:
var now = new Date();
document.getElementById('txtDate').value = now.getDate() + '/' + now.getMonth()+ '/' + now.getYear();
or in markup (using System.Web.UI.WebControls.TextBox.Text property, it has no Value property):
<asp:TextBox ID="txtDate" runat="server" Text="<%# DateTime.Today.ToShortDateString() %>" />
and after that call this.DataBind(); or not for page, but your TextBox's parent control.
See this similar question.
As you've seen, you can't use the <%= %> construct to set a property of a server control.
The usual way to set a property in markup is to use a <%# data-binding expression %>

Categories

Resources