I need to create a webform where users can add, update, delete, retrieve customer data from a table in an SQL database.
Should have textboxes for each field in the table so that the users can enter details of the fields to update the table in the DB.
What im having trouble with is in the code behind the form i need to make a clear method to clear all the textboxes and the message label.
I also need to set validation requirements for each textbox. But i am unsure how to do this properly.
The textboxes are;
CustID, Firstname, Surname, Gender, Age, Address1, Address2, City, Phone, Mobile, Email, Confirm Email.
Now my main question is, how do i validate the textboxes? For example;
CustID is required. & Must be unique. Must be an integer and must be between 1 & 1000.
You should use RequiredValidator for example
http://www.w3schools.com/aspnet/control_reqfieldvalidator.asp
This will perform validation before submitting data to server ;)
There are also other type of validator, like RangeValidator (for the need to check if the integer is between 1 and 1000).
Example:
<asp:RangeValidator ControlToValidate="youtField" MinimumValue="1" MaximumValue="1000" Type="Integer" Text="The field must be between 1 and 1000" runat="server" />
You can also add a ValidationGroup="save" for example to all your validators and to the button that user should click to save and update data.
Asp.net Have some (5 main types) server validation control's , You can use the validations for your requirement
See this image for understanding validation controls (The image referred from )
More understanding by this MSDN sit3
and here is link for all validation control sample's : click me
Here could be an example for ASP/ MVC - because you have forgotten to specify which technology from ASP. Forms or MVC ?!?
This bellow aplies to mvc and the other attributes are allready defined by the users before me.
Note that the RemoteAttribute can verify a function (validation function) .
namespace ModelValidation.Models {
public class Appointment {
[Required]
[StringLength(10, MinimumLength = 3)]
public string ClientName { get; set; }
[DataType(DataType.Date)]
[Remote("ValidateDate", "Home")]
public DateTime Date { get; set; }
public bool TermsAccepted { get; set; }
}
}
To apply validation on a model property that describes a TextBox, then a good proactice is to use TextBoxFor<>(). Like that:
#Html.TextBoxFor((model) => model.ClientName )
You can clear all your controls values by either redirecting to user to another page telling him that form is submitted, New Registration button to redirect user again to Registration page, However if you don't want that you can pick up each control and reset them either in Cs.file or using javascript,
foreach (Control ctrl in form1.Controls)
{
if (ctrl is TextBox)
{
TextBox tb = (TextBox)ctrl;
tb.Text = string.Empty;
}
else if (ctrl is DropDownList)
{
DropDownList dl = (DropDownList)ctrl;
dl.SelectedIndex = 0;
}
else if (ctrl is CheckBox)
{
CheckBox cb = (CheckBox)ctrl;
cb.Checked = false;
}
}
For your validation purpose i strongly suggest you to read about validation in Asp.net , here is a good tutorial you can learn from here
To clear all textbox you can try something like this
foreach (var item in Page.Controls)
{
if (item is TextBox)
{
((TextBox)item).Text = "";
}
if (item is DropDownList)
{
((DropDownList)item).SelectedIndex= 0;
}
//and the other types
}
For the part of validation you have to set the validation fields that you desire and bind it to the field directly on the .aspx page
<asp:textbox ID="Name" runat="server" TabIndex="1"/>
<asp:RequiredFieldValidator ID="rfvName" ControlToValidate="Name" runat="server" ErrorMessage="Name is required">
<asp:ValidationSummary ID="ValidationSummary1" runat="server" DisplayMode ="BulletList" ShowSummary ="true" HeaderText="Errors:" />
When you try to save and one of the condition of your validators returns false, the validation summary will show all the errors written in the errormessage attribute.
Related
End Goal
I have a textbox where the user enters data, and have a "CustomValidator" that checks to see if the textbox entry exist in database. If so, I want data from the database to populate other text boxes, If not, I want to enable a textbox that allows the user to manually enter the data in the other fields.
Example: User Enters a code, validator checks if code is valid. If code is valid, the items associated with that code populate fields, if the code is invalid they get an error message warning them that the code is not valid, but they may continue manually
I know I can use textbox.enabled to change status of the field.
I know how to change the error message
What I don't know is how to do is:
Use custom validator to open a sqlconnection and validate against a list generated by it.
Perform actions based on validations pass/fail status.
Just a kick in the pants to find the information about those two would thing be gratefully appreciate.
Google has not been my friend concerning those two things.
Well, in most cases, you just drop in a validator control, and it wires up the client side JavaScript all automatic for you. This works great for say email text box, or numbers, or whatever. And this type of validation is nice, since no server side code, or even a round trip occurs here.
While dropping in a validator control DOES have and allow server side code (code behind)? I don't think you get much of any advantage here then just coding this out.
I mean, user types something into text box. They will have to tab, or hit some search button or what not, right?
so, pull the data (or find out the data dont' exist).
And your grouping of conrols? Just put them all inside of a panel.
Now, you can simple enable or "disable" the whole panel and group of controls with great ease.
So, say I have a hotel "ID" prompt. You type in a number. If hotel exists, then we display the information and DISABLE the panel. User can see the panel, but not edit.
Or, if no value found, then display message, but ALLOW the user to edit those text fields. So, thinking about this problem, I don't think it is a job for validators, and worse you need the means to enable/disable a whole group of controls.
So, say we have this markup up:
Enter Hotel ID:
<asp:TextBox ID="HotelID" runat="server"></asp:TextBox>
<asp:Button ID="cmdSearch" runat="server" Text="Verify"
style="margin-left:15px" CssClass="btn"
/>
<br />
<asp:Label ID="lblmsg" runat="server" Text=""></asp:Label>
<br />
<asp:Panel ID="HotelInfo" runat="server" Visible="false">
<div style="float:left;width:15%">
<div style="text-align:right">
First Name :<asp:TextBox ID="txtFirstname" runat="server" Width="150"></asp:TextBox> <br />
Last Name :<asp:TextBox ID="txtLastname" runat="server" Width="150"></asp:TextBox> <br />
Hotel Name :<asp:TextBox ID="txtHotel" runat="server" Width="150"></asp:TextBox> <br />
City :<asp:TextBox ID="txtCity" runat="server" Width="150"></asp:TextBox> <br />
Active :<asp:CheckBox ID="Active" runat="server" Width="150"></asp:CheckBox>
</div>
</div>
</asp:Panel>
So, the panel visible = false.
The user will see this this (non valid ID).
So, user gets a message - can edit the controls.
but, if we type in a valid id, then they user sees this:
note how the data display - but we can NOT edit - since we disabled the panel.
I suppose you might have some additonal buttons like continue etc., but you get the general idea here.
The code for the button to verify?
This:
Protected Sub cmdSearch_Click(sender As Object, e As EventArgs) Handles cmdSearch.Click
Dim strSQL = "SELECT * FROM tblHotels WHERE ID = #ID"
Using conn = New SqlConnection(My.Settings.TEST4)
Using cmdSQL = New SqlCommand(strSQL, conn)
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = HotelID.Text
Dim rstData = New DataTable
conn.Open()
rstData.Load(cmdSQL.ExecuteReader)
If rstData.Rows.Count = 0 Then
' not found. Display message
lblmsg.Text = "Not found - enter values or search again"
' display panel
HotelInfo.Visible = True
HotelInfo.Enabled = True ' allow edit of controls
Else
' hotel found
lblmsg.Text = "Hotel found"
' display panel
HotelInfo.Visible = True
HotelInfo.Enabled = False ' disable edits
' now fill controls with data
Dim OneRow As DataRow = rstData.Rows(0)
txtHotel.Text = OneRow("HotelName")
txtCity.Text = OneRow("City")
txtFirstname.Text = OneRow("FirstName")
txtLastname.Text = OneRow("LastName")
End If
End Using
End Using
End Sub
Edit: Sorry - I see this was for c#
Here is a c# version:
string strSQL = "SELECT * FROM tblHotels WHERE ID = #ID";
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = HotelID.Text;
DataTable rstData = new DataTable();
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
if (rstData.Rows.Count == 0)
{
// not found - display message
lblmsg.Text = "Not found - enter values or search again";
// display panel
HotelInfo.Visible = true;
HotelInfo.Enabled = true; // allow edit of controls
}
else
{
// hotel found
lblmsg.Text = "Hotel found";
// display panel
HotelInfo.Visible = true;
HotelInfo.Enabled = false; // disable edits
//now fill controls with data
DataRow OneRow = rstData.Rows[0];
txtHotel.Text = OneRow["HotelName"].ToString();
txtCity.Text = OneRow["City"].ToString();
txtFirstname.Text = OneRow["FirstName"].ToString();
txtLastname.Text = OneRow["LastName"].ToString();
}
}
}
Edit:#3: Using a validator
Note that you ARE free to drop in a custom validator control. and that control WILL require that the textbox has auto-postback = true.
So at this point in time? All the extra work of using a custom valuator will STILL result in a post-back, will STILL require that the textbox has autopostback = true.
Hence given that you want to call server side code, then you might as well just set the text box auto postback=true, and use the text changed event of that text box. In both cases, you going to suffer a post-back, and thus the concept of a use a client side validator to prevent the page post-back is not something you gain, or achieve by using a custom validator + server side code for that validator.
I'm currently working on an asp.net web form that uses Knockout, Bootstrap, and JQuery. I'm having an issue with data persistence through "Wizard steps."
What I would like to do is take in the mailing state of the client and persist it through to other pages, from there use Knockout to make fields visible and also create validation.
I've read that you can use hidden states to accomplish this but I've had issues getting the value to pass to Knockout and ultimately getting the other fields to show.
Here is the c# that does all the steps page to page.
protected void StepChanged(object sender, EventArgs e)
{
if (IsPostBack)
{
if (QuoteWizard.ActiveStepIndex == 0)
txtFirstName.Focus();
if (QuoteWizard.ActiveStepIndex == 1)
{
Session["State"] = ddlState.Value;
rblMailAddr.Focus();
}
if (QuoteWizard.ActiveStepIndex == 3)
{
txtDriverFName1.Value = txtFirstName.Value;
txtDriverMI1.Value = txtMI.Value;
txtDriverLName1.Value = txtLastName.Value;
String DOB;
DOB = Convert.ToDateTime(txtDOB.Value).ToString();
txtDriverDOB1.Value = DOB;
txtDriverFName1.Focus();
}
I find it odd that the txtDriverFName1.Value = txtFirstNAme.Value; passes properly but I can't get the state from a drop down list or the date of birth to pass from one step to the other.
<select id="ddlState" runat="server" class="form-control" data-bind="value: MailState, updateValue: 'afterkeydown'">
Followed by the list of states, then I try to pass it to knockout to make fields visible:
self.MailState = ko.observable("", { persist: "MailState" });
However, once I reach the next step the values in the ViewState are dropped and
<div class="btn-group" data-toggle="buttons" style="padding-left: 10px" data-bind="visible: MailState() == 'CA'">
no longer becomes visible even when CA is selected in the previous viewstate.
So how would I persist the value of my drop down list through 2 or more steps in the QuoteWizard.ActiveStepIndex and have that assigned to "MailState()" subsequently activating Knockout?
in data-bind the bindinghandler handle to excute expression, then visible bindinghandler will unwrap it to value from observable. But in your code you use
data-bind="visible: MailState == 'CA'" //MailState is observalbe then like function() == 'CA' - that not right
should change to:
data-bind="visible: MailState() == 'CA'"
My question is about checkbox boolean value.
See the image below (image is of a View where user chooses the "seminar") and my current implementation.
//in the model, "Popunjen" is checkbox value which displays if a cert
//"seminar" is full or not. Value is set mannually on the "admin" page
public bool Popunjen { get; set; }
I need a functionality where, if user clicks "Upiši se" (Enroll in eng.) on "Seminar" where "Popunjen" or "Full" is true (for ex. last seminar in list), some sort of error messagge is displayed.
Is this best done on the View code of this page? And what would be the code behind it?
Without seeing the code of your MVC, I suppose you're building the View from a Controller [HttpGet] and the table rows are populated from DB query. You could check the value of the "Popunjen" and if it's true disable the "Upiši se", something like:
<td>
#if (item.Popunjen == true)
{
// disable "Upiši se"
// don't show it
}
else
{
// enable "Upiši se"
}
</td>
I want to validate my user control whenever postback occurs. This is the property inside usercontrol wish I want to validate:
public string Text
{
get
{
return DateTextBox.Text;
}
set
{
DateTextBox.Text = value;
}
}
The Text Property always must have format like "YYYY/MM/DD". I want wherever user add this control to every page, when user submits any button, if the Text is not valid, button submit event does not raise. The main problem is that i want this works without altering any page. I means without checking something like Page.IsValid.
You can do this by adding ASP.Net validation controls to your .ascx markup code.
Try adding the following code
<asp:CompareValidator
id="dateValidator" runat="server"
Type="Date"
Operator="DataTypeCheck"
ControlToValidate="DateTextBox"
ErrorMessage="Please enter a valid date.">
</asp:CompareValidator>
<asp:RequiredFieldValidator
ID="RequiredFieldValidator1"
ControlToValidate="DateTextBox"
runat="server"
ErrorMessage="Required!">
</asp:RequiredFieldValidator>
But, the problem with this method is all buttons (Save or Submit) not having CauseValidation=False will try to validate this TextBox.
To overcome this issue you need to
If buttons are in the user control add a ValidationGroup to all controls (TextBox, Validation controls, buttons etc)
If buttons are in your pages
add a public property to your control to hold the ValidationGroup and assign this value to all controls and all the buttons that need to validate.
Try below code:-
public string Text
{
get
{
return DateTextBox.Text;
}
set
{
try
{
DateTime d = DateTime.ParseExact(value, "yyyy/MM/dd",CultureInfo.InvarientCulture);
DateTextBox.Text = value;
}
catch(Exception ex)
{
//// Code when it does not match format.
}
}
}
I have taken over maintenance of a site that makes calls through a WCF service. There is a validation summary that displays in a message box for some validators on the client-side. I also have a label that fires if any exceptions arise from my web service calls. After tweaking the layout, the label sits in an inconvenient spot. I want to know if there is a way to display the label text in the validation summary should the exception fire in the code behind.
Any advice is appreciated.
Example in cs file:
bool ResultUserExistence = register.CheckUniquenessUserID(txtUserId.Text);
if (ResultUniquenessEmail == null)
{
continue through code...
}
else
{
lblException.Text = "Please choose a different user name. The current user name is already registered.";
}
Validation Summary:
<asp:ValidationSummary ID="valSummary"
runat="server"
HeaderText="Please correct the following error(s):"
DisplayMode="List"
ForeColor="#FF9999"
ShowMessageBox="True"
ShowSummary="False" />
As notied in this answer you could create a custom validator, and set the message on that, which will make the message show up in your validation summary.
bool ResultUserExistence = register.CheckUniquenessUserID(txtUserId.Text);
if (ResultUniquenessEmail == null)
{
continue through code...
}
else
{
var err As new CustomValidator()
err.ValidationGroup = "UserUniqueness";
err.IsValid = False;
err.ErrorMessage = "Please choose a different user name. The current user name is already registered.";
Page.Validators.Add(err);
}
Ideally this would be factored out into a method for reusability.