asp.net usercontrol SetFocusOnError - asp.net

I have a aspx page that several of the same usercontrols on the page. The usercontrol houses a textbox that has a Required field validator on it. The validator works but the setonfocus="true" does not seem to be working, further more, the button the aspx page when the validator shows the error message, the button still fires the code behind.
Here is what the aspx page looks like as far as the user control and the the button.
ucTB:ucTextBox ID="ucTextR" runat="server" ValidationGroup="txtRequired" Required="_true"
asp:Button ID="btnSave" runat="server" Text="Click" ValidationGroup="txtRequired"
and the usercontrol validator
asp:RequiredFieldValidator ID="rfTextBox" runat="server" ControlToValidate="txtTextBox"
SetFocusOnError="true" ErrorMessage="Required Field" EnableClientScript="false"
the user control has been wired to grab the validator from the aspx page and use it in the usercontrol... something like this
Public Property ValidationGroup() As String
Get
Return CType(ViewState("ValidationGroup"), String)
End Get
Set(ByVal Value As String)
ViewState("ValidationGroup") = Value
End Set
End Property
Protected Sub AssignValidation()
For Each control As Control In Me.Controls
Dim [property] As PropertyInfo = control.[GetType]().GetProperty("ValidationGroup")
If [property] Is Nothing Then
Continue For
End If
[property].SetValue(control, ValidationGroup, Nothing)
Next
End Sub
and i load the AssignValidation on page_load
anyway.. hope this is the info you need to point me in the right direction.
What i'm looking to do is if the required field validator to put the focus on the usercontrol if there is nothing in the usercontrol text box and also for the button on the aspx page not to fire.. like i think it behaves if you use a validator on a aspx page with no usercontrol
thanks
shannon

You can't set the user control to visible because it's not a visible container. You can set the focus yourself programmatically. See this:
http://forums.digitalpoint.com/showthread.php?t=282224
Or, you can programmably set the validator to the ID of the textbox within the user control; expose a textboxID property in the user control code-behind which returns the textbox's ID, and have your page assign the validator's controltovalidateID to this.

Related

Need to find control in an ascx, which is inside an aspx page, which is inside a master page

I'm using VS2010.
I need to find a control (label, textbox, etc) inside an ascx, which is inside an aspx page, which is inside a master page.
control - ascx - aspx - master.page
I'm trying these commands from my ascx.vb, but no one successfully:
ddlAno = CType(Page.FindControl("myASCX").FindControl("ddlAno"), DropDownList)
ddlAno = CType(Page.Controls(1).FindControl("ddlAno"), DropDownList)
Got nothing as dropdownlist control.
One thing you can do is create a public property that just returns the control itself. In this case a label named "Label1".
Mark Up:
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
Property:
public Label Label1Control
{
get
{
return Label1;
}
}
Then you can access it in the usercontrol like so. (This is for a usercontrol in Default.aspx).
var label = ((Default) Page).Label1Control;
label.Text = "Hello World";

ASP:Net LinkButton control Postback issue

I have an asp.net linkButton (or imageButton) control in my profile.aspx page. I'am checking Request.Querystring("id") in the page below in the code behind.
http: //localhost:42932/profile.aspx?id=1
When I first load the profile page it is not posted back. It is ok!. When I go to another users profile (the same page just the query string is different) using imageButton control with the adddress;
http: //localhost:42932/profile.aspx?id=2
it is posted back. I dont want it to be posted back. But if I go to this page with a regular html input element like
a href = "http: //localhost:42932/profile.aspx?id=2"
it is not posted back. So I want the image button behave like an html input element.
Here is my imageButton;
ASPX:
<asp:ImageButton ID="imgProfile" ImageUrl="images/site/profile1.png" runat="server"/>
.CS
imgProfile.PostBackUrl = "profile.aspx?id=" + Session["userID"];
Edit:
if (!IsPostBack)
{
Session["order"] = 0;
}
This control is in the page load. So it should be !postback with state I mentioned above. Because all the other functions are working when Session["order"] = 0
Make use of OnCLientClick instead of OnClick, so that you only run client side code. Then, sepcify that you return false;
i.e.
<asp:ImageButton ID="imgProfile" ImageUrl="images/site/profile1.png" runat="server" OnClientClick="return false;" />
But, why use a server control, when this can be done with a normal <img .. html control?
Rather than specifying a PostBackUrl I would recommend using Response.Redirect() in the button click event handler:
public void imgProfile_Click(object sender, eventArgs e){
Response.Redirect("profile.aspx?id=" + Session["userID"]);
}
Or alternatively, just use a Hyperlink control and set the NavigateUrl property during Page_Load:
<asp:HyperLink ID="imgProfile" runat="server"><img src="images/site/profile1.png" /></asp:Hyperlink>
imgProfile.NavigateUrl = "profile.aspx?id=" + Session["userID"];

Set a property of a user control from repeater databound data

I have a user control inside of a repeater that is being bound by a sqldatasource. I get the following error: Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control. EDIT: NEVERMIND Egg on my face. I was getting this databind error because I was binding it somewhere else in an effort to troubleshoot my real problem from last friday but I forgot about it.
WHAT MY REAL PROBLEM IS: The usercontrol is getting bound before the properties get set so it appears as if they are never set. When stepping through I see that they get on the property is hit before the set on the property is hit. For example if I put <%# EVal("Address_ID") %> before the user control I will see the ID displayed but then the user control will display an emptydatatemplate because it is being passed the ID of 0.
<asp:SqlDataSource ID="sqlFacilityAddresses" runat="server" DataSourceMode="DataSet" SelectCommandType="StoredProcedure" SelectCommand="SP_Facility_GetAddresses" ConnectionString="<%$ ConnectionStrings:Trustaff_ESig2 %>">
<SelectParameters>
<asp:Parameter Name="Facility_ID" DbType="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<asp:Repeater ID="repeaterAddresses" DataSourceID="sqlFacilityAddresses" runat="server">
<ItemTemplate>
<Select:Address ID="AddressControl" runat="server" AddressID='<%# EVal("Address_ID") %>' />
</ItemTemplate>
</asp:Repeater>
You could handle the repeater's ItemDataBound-Event in codebehind, get a reference to the UserControl via Item.FindControl and set the property according to the Item.DataItem object and your column Address_ID.
For example(debug to see if the type of your dataitem is really DataRowView):
Sub repeaterAddresses_ItemDataBound(Sender As Object, e As RepeaterItemEventArgs)
' This event is raised for the header, the footer, separators, and items.
' Execute the following logic for Items and Alternating Items.
If (e.Item.ItemType = ListItemType.Item) Or _
(e.Item.ItemType = ListItemType.AlternatingItem) Then
Dim addressControl as AddressControl = DirectCast(e.Item.FindControl("AddressControl", AddressControl)
addressControl.AddressID = DirectCast(e.Item.DataItem, DataRowView)("Address_ID").ToString
End If
End Sub
What exactly does your Address UC look like? You can use your AddressID property to do this: e.g.
private bool _AddressID;
public bool AddressID
{
get { return _AddressID; }
set
{
if (_AddressID != value)
{
//addressid is changed
_AddressID = value;
ReloadMyUC();
}
}
}
The ReloadMyUC method does the job of getting data and rebinding the UC.
I just figured this out. First I changed the repeater event to itemcreated instead of itemdatabound but then the repeater was being databound before the event that was resetting the page was being executed which resulted in a 0 ID being sent to my address user control. What I ended up doing was creating a boolean value for the class page setting it to true on the user control raised event this way when it went through the repeater itemcreated event the first time it wouldn't error out and when it went through the second time it would work correctly. This is probably not a best practices way of accomplishing this result but it works.
Maybe using DataBinder.Eval instead of Eval would help?

Access control on other page in asp.net

How to access control in other aspx page from other aspx page in asp.net
you can use findcontrol
Example to get the textbox text:
string controlValue =((TextBox)( Page.FindControl("uc").FindControl("TextBox1"))).Text;
Note: us is id of usercontrol registered in the aspx page. TextBox1 is the textbox in the usercontrol
Button btn = ((Button)PreviousPage.FindControl("Button1"));
Button1.Text = btn.Text;
Use : PreviousPage
Note : PreviousPage property Gets the page that transferred control to the current page.

ASP.Net CustomValidator in GridView is not fired

I got a Gridview in an UpdatePanel with this EditTemplate:
<edititemtemplate>
<asp:textbox id="txtDistFrom" runat="server" text='<%# Bind("distFrom") %>' width="30" />
<asp:CustomValidator ID="valDistFrom" ValidateEmptyText="True" OnServerValidate="valDistFromTo_ServerValidate" ControlToValidate="txtDistFrom" Text="Missing" ToolTip="Invalid" Display="Dynamic" runat="server" />
</edititemtemplate>
And a simple Server-side function:
Protected Sub valDistFromTo_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)
Dim cv As CustomValidator = CType(source, CustomValidator)
Dim gvr As GridViewRow = cv.NamingContainer
Dim tbV As UI.WebControls.TextBox = gvr.FindControl("txtDistFrom")
If tbV.Text <> "" Then
args.IsValid = False
cv.ErrorMessage = "inhalt ist " & tbV.Text
End If
End Sub
But when debugging this code the server-side function is not fired, whatever it does. It seems it has to do with the gridview, so I cannot access the control directly by its id. Any suggestions?
If you modify your VB to:
Protected Sub valDistFromTo_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)
Dim cv As CustomValidator = CType(source, CustomValidator)
If args.Value <> "" Then
args.IsValid = False
cv.ErrorMessage = "inhalt ist " & args.Value
End If
End Sub
It should work. Note that I'm using args.Value. I use CustomValidators and TextBox within EditTemplates with ControlToValidate set to the TextBox ID all the time and it works, you just can't get the TextBox object the way you're trying it. I think this is far less of a pain and much cleaner than messing around with RowUpdating Event as suggested in TGnat's answer.
In this case you can use a required field validator. Which should work just fine in a grid.
For server side validation I would move the custom validator outside the grid entirely and leave the ControlToValidate property blank. You can move your validation to the RowUpdating event of the grid and set any error messages on the custom validator. Rmember to set the validators IsValid property appropriately.
The problem is related to the ControlToValidate property, because the ID of your text box is not used in repeating elements like GridView, ListView and Repeater. In other words: You have stumbled upon a limitation in ASP.NET's engine.
I am not sure how to solve this problem, though. You might be able do it, by adding the CustomValidator programmatically by attaching a method to the GridView's OnRowBound method.
This article might provide an answer This article might provide an answer: Integrating Asp.Net Validation Controls with GridView at run-time.
I also tend to think that ControlToValidate is the problem. .NET changes the ID of that control at runtime and the custom validator probably isn't picking it up.
I would try adding the customvalidator on RowCreated or RowDatabound using the FindControl()
I had the same problem. When I explicitly set this property in my customvalidator, the server side code fired:
EnableClientScript="false"

Resources