Entering the user number in the text box with the webmethod GetSearchUser returns the name of user.
I have this regular expression to test if an input starts with the letter "a" or "A" and is followed by 6 numbers. On the online validator seems to work.
The problem is that when the user number is replaced with the the name of user this string is not validated. And it is correct.
But how do I then check that user number is entered correctly and validate the string when the user number is replaced with the the name of user?
My code below.
<asp:AutoCompleteExtender
ServiceMethod="GetSearchUser"
ServicePath="prefix.aspx"
MinimumPrefixLength="1"
CompletionInterval="10"
EnableCaching="false"
CompletionSetCount="10"
TargetControlID="txuser"
ID="AutoCompleteExtender1"
runat="server"
FirstRowSelected="false">
</asp:AutoCompleteExtender>
<asp:TextBox ID="txuser" runat="server" BackColor="Yellow" CssClass="pure-u-23-24"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator29" runat="server" ControlToValidate="txuser"
SetFocusOnError="true" ErrorMessage="Required" Text=""
Display="None" ValidationGroup="ValidationSummaryUser"
CssClass="validation-summary-errors-one"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator8" runat="server" ControlToValidate="txuser"
SetFocusOnError="true" ErrorMessage="Required : AXXXXXX" Text=""
Display="None" ValidationExpression="/^(a|A)([0-9]{6})$/" ValidationGroup="ValidationSummaryUser"
CssClass="validation-summary-errors-one"></asp:RegularExpressionValidator>
[ScriptMethod()]
[WebMethod]
public static List<string> GetSearchUser(string prefixText)
{
DataTable Result = new DataTable();
string str = #String.Format("SELECT Name FROM `users` ");
str += String.Format(" WHERE user_number LIKE '" + prefixText + "%' ");
str += String.Format(" ORDER BY Name ASC;");
using (OdbcConnection con =
new OdbcConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
{
da = new OdbcDataAdapter(str, con);
dt = new DataTable();
da.Fill(dt);
List<string> Output = new List<string>();
for (int i = 0; i < dt.Rows.Count; i++)
Output.Add(dt.Rows[i][0].ToString());
return Output;
}
}
EDIT
According to your description, I'm afraid that the <asp:RegularExpressionValidator> is unable to complete two validations at the same time.
What you need might be a custom validator which could do both validation for the text box.
Solution: using <asp:CustomValidator>
You could do validation from both server side and client side (I did it from client side).
It can be used as a combination of RequiredValidator, RegularExpressionValidator and extra custom style validation.
More details, you could refer to below code:
.aspx :
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<ajaxToolkit:AutoCompleteExtender
OnClientItemSelected="itemSelected"
ServiceMethod="GetSearchUser"
ServicePath="AutoCompleteExtenderValidation.aspx"
MinimumPrefixLength="1"
CompletionInterval="10"
EnableCaching="false"
CompletionSetCount="10"
TargetControlID="txuser"
ID="AutoCompleteExtender1"
runat="server"
FirstRowSelected="false">
</ajaxToolkit:AutoCompleteExtender>
<asp:TextBox ID="txuser" runat="server" BackColor="Yellow" CssClass="pure-u-23-24"></asp:TextBox>
<asp:HiddenField ID="hf_txuser" runat="server" />
<asp:CustomValidator ID="CustomValidatorFortxuser" runat="server"
ClientValidationFunction="custom_validation" ControlToValidate="txuser"
Display="Dynamic" ErrorMessage="Required AXXXX or Valid UserName"
ValidationGroup="ValidationSummaryUser" ValidateEmptyText="true"></asp:CustomValidator>
<br />
<asp:Button ID="SubmitBtn" runat="server" ValidationGroup="ValidationSummaryUser" Text="Submit" OnClick="Submit_Click" />
<asp:Label ID="Label1" runat="server"></asp:Label>
</div>
Javascript code:
<script type="text/javascript">
function itemSelected(sender, ev) {
//When selected value from the return list, it will be kept in the hidden field for the following validation
var selectedValue = ev._value;
$('#<%= hf_txuser.ClientID%>').val(selectedValue);
}
function custom_validation(source, arguments) {
if (arguments.Value == "") {
arguments.IsValid = false;
} else {
//Valid if one of checks pass: fulfill the regex or equals to hidden field value. No worries about the empty content
arguments.IsValid = (regexValidate(arguments) || arguments.Value == $('#<%= hf_txuser.ClientID%>').val());
}
if (!arguments.IsValid) {
$('#<%= Label1.ClientID%>').text("");
}
}
function regexValidate(input) {
var patt = /^(a|A)([0-9]{6})$/;
return patt.test(input);
}
</script>
.cs code:
protected void Submit_Click(object sender, EventArgs e)
{
Label1.Text = txuser.Text + " Submit successfully!";
}
You should include Jquery in the <head> since I have used Jquery in the code for assigning value to the hidden field.
<head runat="server">
<title></title>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
The version could be any one as long as it works for value assignment.
Hope this can help you.
Related
I have two address fields which has 46 textboxes and each one accepts only one character.
For eg.
Address
Line1 : 1.2.3.4....46
Line2 : 1.2.3.4...46
Now on checkbox oncheckchanged event,
I want to copy each character from textbox to another respectively and if checkbox is not checked then line one should be remained as it is.
How to accomplish this?
I tried googling but didn't help much.
<asp:TextBox runat="server" ID="line1_1" MaxLength="1" ></asp:TextBox><br/>
<asp:CheckBox runat="server" ID="if_same" Text="Same" OnCheckedChanged="if_same_CheckedChanged" AutoPostBack="true" />
<asp:TextBox runat="server" ID="line2_1" MaxLength="1" ></asp:TextBox><asp:TextBox runat="server" ID="line2_46" MaxLength="1" ></asp:TextBox>
protected void if_same_CheckedChanged(object sender, EventArgs e)
{
set_per_local();
}
public void set_per_local()
{
if (if_same.Checked == true)
{
checkIfNullEmpty();
disablelocal();
string line1_address = string.Concat(line1_1.Text,line1_46.Text);
try
{
for (int i = 0; i < line1_address.Length; i++)
{
line2_1.Text = line1_address[0].ToString();
line2_46.Text = line1_address[45].ToString();
}
}
catch (Exception)
{
throw;
}
}
else
{
Enablelocal();
}
}
public void checkIfNullEmpty()
{
if (string.IsNullOrEmpty(line1_1.Text)) line1_1.Text = " ";
if (string.IsNullOrEmpty(line1_46.Text)) line1_46.Text = " ";
}
public void disablelocal()
{
local_line1_address1.Enabled = false;
local_line1_address46.Enabled = false;
}
public void enablelocal()
{
local_line1_address1.Enabled = true;
local_line1_address46.Enabled = true;
}
I think this could be a better candidate for a client-side javascript or jQuery etc. Also, if you have followed a logical pattern for naming those 46 textboxes, in your javascript you could hook into the checkbox.changed event and start a loop walking each of the source fields and replace the target field textbox with the source value. Something like
<script>
$(".checkbox").change(function() {
if(this.checked) {
alltextboxes();
}
});
function copy alltextboxes()
{
for (int i = 0; i < 46; i++)
{
document.getElementById(tgtTbox+i).value = document.getElementById(srcTbox+i).value
}
}
</script>
Disclaimer: I have not tested this code though. I just typed it into the answer. based on your requirement, this code may need small modifications. Just note that this only works if your naming convention for the textbox labels follow a pattern (like "SourceText1, SourceText2, TargetText1, TargetText2 etc.").
I found this site more helpful.
http://www.dotnetspark.com/kb/3125-how-to-copy-textbox---text-to-another-one.aspx
<asp:TextBox runat="server" ID="TextBox1" MaxLength="1" size="1"></asp:TextBox>
<asp:TextBox runat="server" ID="TextBox2" MaxLength="1" size="1"></asp:TextBox>
<asp:TextBox runat="server" ID="TextBox3" MaxLength="1" size="1"></asp:TextBox>
<asp:TextBox runat="server" ID="TextBox4" MaxLength="1" size="1"></asp:TextBox>
<asp:CheckBox runat="server" ID="CheckBox1" Text="Same as above" onclick="CopyText()" />
<asp:TextBox runat="server" ID="iBox1" MaxLength="1" size="1"></asp:TextBox>
<asp:TextBox runat="server" ID="iBox2" MaxLength="1" size="1"></asp:TextBox>
<asp:TextBox runat="server" ID="iBox3" MaxLength="1" size="1"></asp:TextBox>
<asp:TextBox runat="server" ID="iBox4" MaxLength="1" size="1"></asp:TextBox>
<script type="text/javascript">
function CopyText() {
var cb = document.getElementById('CheckBox1');
var tb1 = document.getElementById('TextBox1');
var tb2 = document.getElementById('TextBox2');
var tb3 = document.getElementById('TextBox3');
var tb4 = document.getElementById('TextBox4');
var tb11 = document.getElementById('iBox1');
var tb12 = document.getElementById('iBox2');
var tb13 = document.getElementById('iBox3');
var tb14 = document.getElementById('iBox4');
if (cb.checked) {
tb11.value = tb1.value;
tb12.value = tb2.value;
tb13.value = tb3.value;
tb14.value = tb4.value; }
else {
tb11.value = '';
tb12.value = '';
tb13.value = '';
tb14.value = ''; }
}
}
<script>
Framework: ASP.NET 4.5 | Database: MSMMS
My demo application is supposed to populate textboxes with dynamic data when a selection is made from a dropdown list. I've added a button, that when pressed fires, an OnClick event that is supposed to assign values from the DB to the appropriate textboxes. Right now my code looks like:
protected void btnChoose_Click(object sender, EventArgs e)
{
API_DatabaseEntities1 db = new API_DatabaseEntities1();
var customer = (from c in db.Customers
where c.CustomerID == 4
select c).FirstOrDefault();
if (customer == null)
{
return;
}
if (ddlCustomer.SelectedValue == "Marisol") {
tbDescription.Text = customer.ToString();
tbFName.Text = customer.Fname;
tbSocial.Text = customer.SSN;
tbDOB.Text = customer.DOB.ToString();
tbFName1.Text = customer.Fname;
tbMName.Text = customer.Mname;
tbLName.Text = customer.Lname;
tbPrimaryPhone.Text = customer.PrimaryPhone;
tbSecondaryPhone.Text = customer.SecondaryPhone;
tbAdd1.Text = customer.Address;
tbCity.Text = customer.City;
tbZip.Text = customer.Zip;
tbEmail.Text = customer.Email;
tbMonLease.Text = customer.MortLeaseAmt;
tbEmployer.Text = customer.Employer;
tbPosition.Text = customer.Position;
tbHireDate.Text = customer.HireDate.ToString();
tbWorkPhone.Text = customer.WorkPhone;
tbGross.Text = customer.GrossIncome;
}
Debug.WriteLine(tbPosition.Text);
}
When the button is clicked, the page sends a request to the DB, but the textboxes remain blank. I am returning a value from the database, but it's not populating. Here is some code from my front page:
<form id="form1" runat="server">
<asp:DropDownList ID="ddlCustomer" runat="server" DataSourceID="SqlDataSource1" DataTextField="Fname" DataValueField="CustomerID"></asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:APIConnectionString %>" SelectCommand="SELECT [CustomerID], [Fname], [Lname] FROM [Customer] ORDER BY [Fname]"></asp:SqlDataSource><br /><br />
<asp:Button ID="btnChoose" runat="server" Text="Choose Test Case" OnClick="btnChoose_Click" /><br /><br />
Description of Goods and/or Services:<asp:TextBox ID="tbDescription" runat="server"></asp:TextBox><br /><br />
<div>
Membership #:<asp:TextBox ID="tbMembership" runat="server"></asp:TextBox> Ext.: <asp:TextBox ID="tbExt1" runat="server"></asp:TextBox>
First Name:<asp:TextBox ID="tbFName" runat="server"></asp:TextBox><br /> <br /><br />
Soc Sec No.: <asp:TextBox ID="tbSocial" runat="server"></asp:TextBox> Date of Birth:<asp:TextBox ID="tbDOB" runat="server" ></asp:TextBox>
</div><br /> <br />
I'm not sure if the problem is from the code behind or from the front page design. Any help would be appreciate. Thank you.
It looks like your code is checking for a selection in the drop-down list of the name "Marisol" - however, the "Value" field of the drop-down list is configured to use the CustomerID column. So this code populating the fields will never execute.
Maybe you should instead be using ddlCustomer.SelectedValue in the WHERE clause of your query.
I am designing a web page in asp.net C# named "myprofile". The structure is as follows from top to bottom: file upload control(for logo), drop down (for hotel type), a rich text box (for contact information - extra: bold, italics, hyperlink etc features), drop down (for location).
My problem is maintaining the values of file upload control and rich text box on postback. Also I am unable to insert the values in database as nothing is happening. I tried many things. Finally, I set my design as follows:
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<fieldset style="width:30%">
<legend>Update Panel-1</legend>
<br />(Type of Hotel)<br /><br />
<asp:DropDownList ID="DropDownTypeOfHotel" runat="server" CssClass="cssdropdown"></asp:DropDownList>
<br />(Contact Information Here)<br /><br />
<asp:TextBox ID="RichTextBoxContactInfo" runat="server"></asp:TextBox>
<br />(Location)<br /><br />
<asp:DropDownList ID="DropDownListLocation" runat="server" CssClass="cssdropdown"></asp:DropDownList>
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<fieldset style="width:30%">
<legend>Update Panel-2</legend>
<asp:Label ID="Label1" runat="server" Text="" ForeColor="Red"></asp:Label>
<br /><br />
<asp:Button ID="btnUpdate2" runat="server" Text="Update Both Panels" OnClick="btnUpdate2_Click" />
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>
My code for the same lies here:-
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
loadHotelType();
}
Page.Form.Attributes.Add("enctype", "multipart/form-data");
}
protected void btnUpdate2_Click(object sender, EventArgs e)
{
if (DropDownTypeOfHotel.SelectedIndex > 0)
{
if (DropDownListLocation.SelectedIndex > 0)
{
if (!string.IsNullOrEmpty(RichTextBoxContactInfo.Text))
{
Label1.Text = "Cool!";
insert();
}
else
{
Label1.Text = "Kindly add contact info!";
}
}
else
{
Label1.Text = "Kindly select location!";
}
}
else
{
Label1.Text = "Kindly select type of hotel!";
}
}
public void loadHotelType()
{
DropDownTypeOfHotel.Items.Insert(0, "--Select Type of Hotel/Supplier--");
DropDownTypeOfHotel.Items.Insert(1, "2 star");
DropDownTypeOfHotel.Items.Insert(2, "3 star");
DropDownTypeOfHotel.Items.Insert(3, "5 star");
DropDownListLocation.Items.Insert(0, "--Select Location of Hotel/Supplier--");
DropDownListLocation.Items.Insert(1, "Canada");
DropDownListLocation.Items.Insert(2, "USA");
DropDownListLocation.Items.Insert(3, "LA");
}
public void insert()
{
int img_logo = 0;
static byte[] btlogo_img;
if (FileUpload1.PostedFile.ContentLength != 0)
{
btlogo_img = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile up1 = FileUpload1.PostedFile;
up1.InputStream.Read(btlogo_img, 0, (int)FileUpload1.PostedFile.ContentLength);
img_logo = 1;
}
if (img_logo == 1)
{
con1.Close();
con1.Open();
SqlCommand cmd = new SqlCommand("insert into file values('" + FileUpload1.PostedFile.FileName + "','" + btlogo_img + "')", con1);
cmd.ExecuteNonQuery();
con1.Close();
}
else
{
Label1.Text = "Kindly select logo!";
}
}
Kindly suggest me with the same.
The easiest solution I found was to keep the controls, that loses value on postback, outside update panel and keep all other controls inside update panel.
It really worked for me!
I have a repeater that I populate from a database:
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(#"SELECT CommunityName, CID, Budget FROM Donation WHERE Year = year(getdate()) ORDER BY CommunityName", conn);
conn.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet myDataSet = new DataSet();
adp.Fill(myDataSet);
myRep.ItemDataBound += new RepeaterItemEventHandler(myRep_ItemDataBound);
myRep.DataSource = myDataSet;
myRep.DataBind();
}
void myRep_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
var textbox = e.Item.FindControl("community");
textbox.ClientIDMode = ClientIDMode.Static;
textbox.ID = "community" + (e.Item.ItemIndex + 1);
}
Repeater:
<asp:UpdatePanel ID="UpdatePanel" runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:Repeater ID="myRep" runat="server">
<ItemTemplate>
<div class="form-group">
<asp:Label ID='thisLbl' runat="server" Text='<%# Eval("CommunityName") %>' />
<asp:TextBox runat="server" ID="community" Text='<%# Eval("Budget") %>' CssClass="form-control" />
</div>
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
This creates 6 textboxes with labels and values, now my question is how do I detect which of these boxes belongs to the record it was initially pulled from in the database? I want to be able to modify the value in these boxes and hit a button to save them back to the database but I can't seem to wrap my head around getting them to the proper records.
Should I set the ID of the textbox to something I can parse through and match with the proper record? In the ItemDataBound?
You have to put a hidden field inside the repeater item template that takes the value from budget, and another hidden field to keep the CID value that has to be read in the post back request. Of course you need also a button and its click event handler.
<asp:Repeater ID="myRep" runat="server">
<ItemTemplate>
<div class="form-group">
<asp:Label ID='thisLbl' runat="server" Text='<%# Eval("CommunityName") %>' />
<asp:TextBox runat="server" ID="txtBudget" Text='<%# Eval("Budget") %>' CssClass="form-control" />
<asp:HiddenField runat="server" ID="hdOriginalBudget" Value='<%# Eval("Budget") %>' />
<asp:HiddenField runat="server" ID="hdCID" Value='<%# Eval("CID") %>' />
</div>
</ItemTemplate>
</asp:Repeater>
<br />
<asp:Button ID="btn" runat="server" OnClick="btn_Click" />
In your code behind you need to loop inside the repeater to check whether the text box has been changed by comparing its value to the hidden field. After you save the budget value in the database you need to realign the hidden field value to the the new value entered by the user, otherwise you will always save that value after each post back:
protected void btn_Click(object sender, EventArgs e)
{
foreach (RepeaterItem item in myRep.Items)
{
var txtBudget = item.FindControl("txtBudget") as TextBox;
var hdOriginalBudget = item.FindControl("hdOriginalBudget") as HiddenField;
var hdCID = item.FindControl("hdCID") as HiddenField;
if (txtBudget.Text != hdOriginalBudget.Value)
{
//If you enter here means the user changed the value of the text box
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(#"UPDATE Donation SET Budget = #Budget WHERE CID = #CID", conn);
cmd.Parameters.Add(new SqlParameter("#Budget", int.Parse(txtBudget.Text)));
cmd.Parameters.Add(new SqlParameter("#CID", int.Parse(hdCID.Value)));
conn.Open();
cmd.ExecuteNonQuery();
}
//After you write in the database realign the values
hdOriginalBudget.Value = txtBudget.Text;
}
}
}
Take care that my code is missing the most basic validation, so if the user writes an invalid value in the textbox (for example "yyy") it breaks. So please don't put it in production as it is!
I have problems in using CustomValidation control, I want to check if year entered in date of birth text field is less than graduation year selected from a drop down list by 20 years. I think using ClientValidationFunction is much better when i tried to use it:
<asp:CustomValidator ID="BirthYearCustomValidator" runat="server" ControlToValidate="ddlGraduationYear" ErrorMessage="Enter a valid graduation year." SetFocusOnError="true" ValidationGroup="SaveEducationStep" Display="Dynamic" ClientValidationFunction="GraduationYearValidation"></asp:CustomValidator>
here is the script
<script type="text/javascript">
function GraduationYearValidation(sender, args) {
var brithYear = parseInt(new Date(document.getElementById('<%=txtBirthDate.ClientID%>').value).getFullYear());
var gradeYear = parseInt(document.getElementById('<%=ddlGraduationYear.ClientID%>').options[document.getElementById('<%=ddlGraduationYear.ClientID%>').selectedIndex].text);
if ((brithYear - gradeYear) < 20) {
return args.IsValid = true;
}
else {
return args.IsValid = false;
}
}
I get those errors: document.getElementById(...) is null and GraduationYearValidation is not defined.
so, i tried to make it server side by:
<asp:CustomValidator ID="BirthYearCustomValidator" runat="server" ControlToValidate="ddlGraduationYear" ErrorMessage="enter a valid graduation year." SetFocusOnError="true" ValidationGroup="SaveEducationStep" Display="Dynamic" OnServerValidate="BirthYearCustomValidator_ServerValidate"></asp:CustomValidator>
code behind is :
protected void BirthYearCustomValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
int brithYear = Convert.ToDateTime(txtBirthDate.Text).Year;
int gradeYear = Convert.ToInt32(ddlGraduationYear.SelectedValue);
if ((gradeYear - brithYear) < 20)
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}
it doen't work and i searched for the reason i found it may be because i need to write Page.Validate("SaveEducationStep"); and check if Page.IsValid before save, but it still not working with me
any suggestion on both scenarios will be appreciated. thanks.
client side validation is working, check your code
<asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
<asp:DropDownList ID="dddate" runat="server">
<asp:ListItem Text="2014" Value="2014"></asp:ListItem>
<asp:ListItem Text="2013" Value="2013"></asp:ListItem>
<asp:ListItem Text="2012" Value="2012"></asp:ListItem>
<asp:ListItem Text="2011" Value="2011"></asp:ListItem>
</asp:DropDownList>
<asp:CustomValidator ID="CustomValidator1" ValidateEmptyText="true" EnableClientScript="true" runat="server" ErrorMessage="CustomValidator" ValidationGroup="test" ClientValidationFunction="abc" ControlToValidate="dddate"></asp:CustomValidator>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" ValidationGroup="test" />
<script type="text/javascript">
function abc(sender, args) {
var birthYear = parseInt(new Date(document.getElementById('<%=txtDate.ClientID%>').value).getFullYear());
var gradeYear = parseInt(document.getElementById('<%=dddate.ClientID%>').options[document.getElementById('<%=dddate.ClientID%>').selectedIndex].text);
if ((gradeYear - birthYear) > 20) {
return args.IsValid = true;
}
else {
return args.IsValid = false;
}
}
</script>