how to make a validation code for ASP.NET form with VB coding - asp.net

im trying to build a form+attachment that needs to be send to email.
Im using a VB background code (attachementemail.aspx.vb)
and my front (b-16.aspx)
I want the page to check that the user entered a email, name, phonenumber and attachment.
what command do I put in the axp.vb
and what on the .aspx
tried just about anything.

The simplest way is to use validators eg RequiredFieldValidator for mandatory fields. You can also implement CustomValidators for custom logic.
See http://msdn.microsoft.com/en-us/e5a8xz39.aspx for the available validators

At it's basic level you could use RequiredFieldValidator and CustomValidation in your form. You can use some regex logic for email, I use this but there are many out there:
Regex(#"\w+([-+.]\w+)#\w+([-.]\w+).\w+([-.]\w+)*")
Personally I use client side javascript before it hits the server and then I re-validate the entries once it hits the server. If your using the postback events then you'll need update panels and a scriptmanager (not sure if you are aware of this already, so apologies if teaching you to suck eggs!).
Here is an example:
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage="RequiredFieldValidator" ControlToValidate="TextBox1"></asp:RequiredFieldValidator>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
Code behind (sorry this is in c#)
protected void Button1_Click(object sender, EventArgs e)
{
if (RequiredFieldValidator1.IsValid)
{
Label1.Text = "Has content";
}
else
{
Label1.Text = "Not valid";
}
}
Note that the required field validator has it's own methods to display a "hey you haven't entered content here my friend" message, but i have added that to the label instead.

Related

Unable to call a button for asp.net website

So the problem here is that i am unable to call a button that another developer created and handed over the site to me.
He is not available and I am not very much into ASP.net but really need to figure this out.
The code is:
<div class="clearfix">
<asp:UpdatePanel runat="server" id="UpdatePanel2">
<ContentTemplate>
<asp:Label ID="lblDesc" runat="server" Text=""/>
<asp:LinkButton ID="btnMore" runat="server" Text="more"/>
</ContentTemplate>
</asp:UpdatePanel>
</div>
The btnMore should call a button at server making the word more to be a link that will expand the div to get a blog post from the database.
It is not doing so.
Any idea why??
Your LinkButton has no associated action with it. You need to set the OnClick attribute to the function on the server side that has the correct signature. For example...
<asp:LinkButton ID="btnMore" runat="server" Text="more" OnClick="btnMore_Click" />
Then in your code behind...
protected void btnMore_Click(object sender, EventArgs e)
{
//do your server side stuff
}

asp.net required field validation called on every button action

I wrote a simple asp.net code with the asp.net required validator control, the problem is that I only have one submit button called GO, and a dropdownlist that looks for the selection :
clear, submit, cancel.
No matter what option is selected, the required field validation is being fired.
Is there a way to code the page so only when the selected value is Submit it validates?
<asp:TextBox runat="server" id="txtName" />
<asp:RequiredFieldValidator runat="server" id="reqName" controltovalidate="txtName" errormessage="Please enter your name!" />
<br /><br />
<asp:DropDownList ID="dpAction" runat="server">
<asp:ListItem>Submit</asp:ListItem>
<asp:ListItem Value="Reset">Reset</asp:ListItem>
<asp:ListItem>Cancel</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="btnAction" runat="server" onclick="btnAction_Click" Text="Go"
Width="40px" />
You will probably have to use a custom validator, and you would need to write the client side code for it also if you want client side validation.
I'm assuming you have a text box or something else that is required when "dpAction" is set to "Submit"?
So for example you would do something like this in your markup
<asp:CustomValidator id="CustomValidator1" runat="server"
OnServerValidate="TextValidate"
ControlToValidate="TextBox1"
ErrorMessage="Text must be specified if Submit is selected">
and in your code-behind
protected void TextValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = dpAction.SelectedValue == "Submit" && !String.IsNullOrEmpty(textbox1.Text);
}
using "required" attribute.
its new in html 5
you should set ValidationGroup for each Validator!
for all controls that you want to be validated and the button to fire the validation:
and the button must have same validaton group with your validator!

asp.net set textbox control in panel contol

I want to set the textbox contol located in the panel control via code
I know to retrieve the inputted value in the textbox control:
string myVal = Request.Form["txtResult"];
I want to set the txtResult.text = "some text";
makeup snippet:
<asp:Panel ID="Panel1" runat="server" Style="display: none" Width="233px">
<asp:TextBox ID="txtResult" runat="server" AutoPostBack="True"></asp:TextBox>
<br />
<div align="center">
<asp:Button ID="OkButton" runat="server" Text="OK" />
<asp:Button ID="CancelButton" runat="server" Text="Cancel" />
</div>
</asp:Panel>
txtResult is not available within code, I tried to see if it is available in the page_load, it's not
texReults was a typo, its txtResult, I updated the ID
the intellisense does not recognize any cntr by the name txtResult
its a new web application and the panel visibility=True
maybee this wil help, above the snipet, I use ScriptManager from the AJAX Exstension
I am aware of he Asnchronius affects, partial potback, etc.
It's a managed control, you should be able to set it on the Page_Load event:
protected void Page_Load(object sender, System.EventArgs e)
{
txtResult.Text = "some text";
}
Update: Based on your update, there are a couple of things that you would need to check:
Spelling: Are you sure you're spelling the control name correctly?
Its ID in your code is "txtResults", but you're referencing it as
"txtResult".
Designer: Did you copy the aspx page or bypass VS in some way for this page? If so check the .designer file for the reference to the control: i.e. "Page1.aspx.designer.cs"
Visibility: Is the Panel control's visibility set to true? If not, then it won't render the controls that are contained within it.
Update 2: If you're doing this through scriptmanager, then I highly recommend that you read through this: http://www.wrox.com/WileyCDA/Section/Using-the-ASP-NET-AJAX-ScriptManager.id-305492.html

RadioButtonList inside UpdatePanel inside Repeater, Can I?

I have a repeater with a RadioButtonList inside the ItemTemplate, but when the RadioButtonList.OnSelectedIndexChanged event fires it generates a full postback. What have I done wrong in my code below? How can I get the OnSelectedIndexChanged to generate an Async Postback?
<asp:UpdatePanel runat="server" ID="UpdatePanel2">
<ContentTemplate>
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="sqlOptions">
<ItemTemplate>
<asp:UpdatePanel runat="server" ID="pnlA">
<ContentTemplate>
<strong>
<%# Eval("Name") %></strong><br />
<asp:RadioButtonList ID="RadioButtonList1"
DataSourceID="sqlOptionValues" runat="server"
DataTextField="id" DataValueField="Id" AutoPostBack="true"
OnSelectedIndexChanged="LoadPrice"
ValidationGroup="options" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
ForeColor="Red" runat="server"
ControlToValidate="RadioButtonList1"
ErrorMessage="Required Field"
ValidationGroup="options" />
<asp:SqlDataSource ID="sqlOptionValues" runat="server"
ConnectionString="<%$ ConnectionStrings:
ConnectionString6 %>"
SelectCommand='<%# "SELECT DISTINCT OptionValue.Name,
OptionValue.Id FROM CombinationDetail
INNER JOIN OptionValue
ON CombinationDetail.OptionValueId = OptionValue.Id
WHERE (OptionValue.OptionId =" +
Eval("Id") + ")" %>'>
</asp:SqlDataSource>
<br />
</ContentTemplate>
</asp:UpdatePanel>
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
Many thanks for any help :)
This is a real-world use case. I have a page with Repeaters, Ajax Accordions inside of other Accordions, Update Panels inside other Update panels, you name it. The page works great, except when I want to update one of the Accordion panels with my RadioButtonList (RBL). Even with the RBL inside an update panel, it causes a postback of the entire page. I tried everything. I finally realized it wasn't me when I noticed my buttons would work just fine. I figure it must be a bug in either the framework or the Ajax Control Toolkit. I did find people reference this link all over the web (http://blog.smarx.com/posts/the-case-of-the-radiobuttonlist-half-trigger.aspx), but this link from 2007 is dead now and probably no longer applicable, so that's no help.
What I ended up doing was going with what works - that submit button. All I did was add an onclick attribute to the RBL to call a hidden button. Now you don't want to set the button to Visible=false because then the button won't appear in the generated markup. Instead, set the button's style to display:none; so that no one will see this hack, because yes, that's what this workaround is - it's a hack, but simple and just as effective as what you'd expect. Don't forget to remove the Autopostback="True" from your RBL.
CAVEAT: Because I'm using a hacked button for the onclick event, it's possible for the user to click in the area of the RBL, but not actually select an item. When this happens, our onclick triggers an AsyncPostBack and the codebehind logic will be processed, so please keep that in mind. To give you an idea of what I mean: all the Page_Load() events will be called, but rbl_Questions_SelectedIndexChanged() won't be if they happen to click in the area of the RBL without actually selecting an item. For my purposes this causes no issues in my logic and has no effect on the user.
Here's the Code:
Somewhere In the .Aspx Page:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:RadioButtonList ID="rbl_Questions" runat="server"
OnSelectedIndexChanged="rbl_Questions_SelectedIndexChanged">
</asp:RadioButtonList>
<asp:Button ID="btn_rbl_Questions" runat="server" style="display:none;"/>
<asp:Label ID="lbl_Result" runat="server" Text="" Visible="false">
</asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
In the Page_Load() event:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
//Instead of using the AutoPostback of the RBL, use this instead.
rbl_Questions.Attributes.Add("onclick",
"document.getElementById('"
+ btn_rbl_Questions.ClientID
+ "').click();");
//Bind your RBL to a DataSource, add items programmatically,
// or add them in the aspx markup.
}
}
In the rbl_Questions_SelectedIndexChanged() event:
protected void rbl_Questions_SelectedIndexChanged(object sender, EventArgs e)
{
//Your code here.
//My code unhid the lbl_Result control and set its text value.
}
Update 05/24/2011
The above "hack" is no longer necessary (I am leaving it above since this was marked as the answer by the author). I have found the best way to do this, thanks to this SO Answer:
Updatepanel gives full postback instead of asyncpostback
The code is much simpler now, just remove what I put in the Page_Load() method and remove the Button I used in the Aspx page and add ClientIDMode="AutoID" and AutoPostBack="True" to the control you want the UpdatePanel to capture.
Somewhere In the .Aspx Page:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:RadioButtonList ID="rbl_Questions" runat="server"
ClientIDMode="AutoID" AutoPostBack="true"
OnSelectedIndexChanged="rbl_Questions_SelectedIndexChanged">
</asp:RadioButtonList>
<asp:Label ID="lbl_Result" runat="server" Text="" Visible="false">
</asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
MS changed how ClientID's are generated in .net 4.0 from "AutoID" to "Predictable" and I guess the ScriptManager or UpdatePanel's weren't updated correctly to use it. I can't find documentation on why that is anywhere or if it was left that way by design.
I seriously don't miss winforms.
Try this:
<asp:UpdatePanel runat="server" UpdateMode="Conditional" ID="pnlA">
You'll also need to setup
<Triggers>
//radio buttons
</Triggers>
Not sure how you'll do that since it's a dynamically built list.

Update Panel and triggers from a repeater control

Hi I found code similiar to the following online. It's seems really great for getting a button buried in a repeater control to trigger a full cycle back to the server.
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<%=DateTime.Now.ToString() %>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="HiddenButton" />
</Triggers>
</asp:UpdatePanel>
<!--Make a hidden button to treat as the postback trigger-->
<asp:Button ID="HiddenButton" runat="server" Style="display: none" Text="HiddenButton" />
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
<ItemTemplate>
<!--when cick the button1, it will fire the hiddenButton-->
<asp:Button ID="Button1" Text="Trigger" CommandArgument='<%# Eval("Id") %>' OnClientClick="$get('HiddenButton').click();return false;"
runat="server" />
</ItemTemplate>
</asp:Repeater>
It uses a hiddenButton to achieve this by hooking the click event of the original button to this one. However my addition to this was the setting of the CommandArgument for the button. I would also need it to be set for the HiddenButton.
Does anyone know a way of going about this?
First I will like to explain the Disadvantage of using the Update Panel using the very same example posted by you.
Below is the Original Code
Output
To display the 22 character string you can check how much data is being received and sent to server. Just imagine following
If you would consider send each request to Database using Update Panel and your GridView is in Update Panel!!!!!!
Suppose you would use ViewState data for each request and with GridView Inside the Update Panel.
Both the above techniques are worst as per my understanding.
Now I will describe you Page Methods
Page Method over Update panel
Page Methods allow ASP.NET AJAX pages to directly execute a Page’s Static Methods, using JSON (JavaScript Object Notation). Instead of posting back and then receiving HTML markup to completely replace our UpdatePanel’s contents, we can use a Web Method to request only the information that we’re interested.
Sample Code
Output
Hope this clearly explains the difference of usage.
Answer to the original Query
You have to register the ItemDataBound event of the below Repeater and use below code for it.
Code Behind
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
Button btn = (Button)e.Item.FindControl("Button1");
btn.OnClientClick = string.Format("SubmitButton('{0}');return false;"
, HiddenButton.ClientID);
}
}
JavaScript
<script type="text/javascript">
function SubmitButton(btn)
{
$("#" + btn).click();
}
</script>
//Alternative
<script type="text/javascript">
function SubmitButton(btn)
{
document.getElementById(btn).click();
}
</script>
Reference & Here
Your HiddenButton control is a server control but you are trying to access it in JQuery using it's ASP.Net ID,
<asp:Button ID="Button1" Text="Trigger" CommandArgument='<%# Eval("Id") %>' OnClientClick="$get('**HiddenButton**').click();return false;"
runat="server" />
A quick way to fix it is to make a separate function,
<script type="text/javascript">
function SubmitButton(btn)
{
$get("#" . btn).click();
}
</script>
and change your button code to ,
<asp:Button ID="Button1" Text="Trigger" CommandArgument='<%# Eval("Id") %>'
runat="server" />
In code behind, in repeater's ItemDataBound event, find the button and HiddenControl and set Button1's OnClientClick property,
Button1.OnClientClick= string.Format("SubmitButton('{0}');return false;",HiddenButton.ClientID);

Resources