how to set the focus to a control by default? - asp.net

i have a login control and a create user control i my web page...i want the cursor to be in the user name text box of the login control when the page loads...how can i do that??
<asp:LoginView ID="LoginView1" runat="server">
<LoggedInTemplate>
Bingo..!!! Youuuuu did it...<asp:LoginName ID="LoginName1" runat="server" />.
</LoggedInTemplate>
<AnonymousTemplate>
<asp:DropShadowExtender ID="DropShadowExtender1" runat="server"
TargetControlID="Panel1"
Rounded="true"
Opacity=".38">
</asp:DropShadowExtender>
<asp:Panel ID="Panel1" runat="server"
BackColor="Silver">
<asp:Login ID="Login1" runat="server"
DestinationPageUrl="~/ViewCart_aspx/ViewCart.aspx"
Height="152px"
Width="396px"
RememberMeSet="True"
OnLoggedIn="ContinueButton_Click" >
<LayoutTemplate>
<fieldset>
<table border="0"
cellpadding="1"
cellspacing="0"
style="border-collapse:collapse;">
<tr>
<td>
<table border="0" cellpadding="0" style="height:152px;width:396px;">
<tr>
<td align="center" colspan="2">
<h3>Log In</h3> </td>
</tr>
<tr>
<td align="right">
<asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">User Name:</asp:Label>
</td>
<td>
<asp:TextBox ID="UserName" runat="server" Width="150px" TabIndex="0"></asp:TextBox>
<asp:RequiredFieldValidator ID="UserNameRequired" runat="server"
ControlToValidate="UserName" ErrorMessage="User Name is required."
ToolTip="User Name is required." ValidationGroup="ctl01$Login1">*</asp:RequiredFieldValidator>
</td>
</tr>
as u can see the UserName textbox is inside the login control..so i cannot access its property..how do i find the control??

EDIT: as you mentioned in comments, you want to set your login button to be clicked as a default button. For this you need to set this button as a default button.
Unfortunatelly, you didn't format you code properly as I asked in a comment to your question. So I assume the login button is located in the same name container as the username text box and its name is btnLogin and you could set this control as a default control with HtmlForm.DefaultButton property, so:
You could use Page.SetFocus for this. It sets the browser focus to the specified control:
Page.SetFocus(txtName);
If you want to reach your UserName textbox, you could use just:
var login1 = LoginView1.FindControl("Login1") as Login;
if (login1 != null)
{
var txtUserName = login1.FindControl("UserName");
if (txtUserName != null)
{
Page.SetFocus(txtUserName);
}
var btnLogin = login1.FindControl("btnLogin");
if (btnLogin != null)
{
Page.Form.DefaultButton = btnLogin.UniqueID;
}
}
But note:
For the LoginView control, when being
added onto a page, at a certain time,
only one Template (anonymous or
loggedIn ) is applied on the Control
instance, so at that time, we can only
retrieve the reference of those
controls in the active template( can't
access those in the non-active
template).

Write the code in Page load event like follows
textbox1.focus();
where ever it may be, by using the ID of the control you have to access the control in the code behind.

The DefaultFocus property seems to be suitable in this case:
// inside page_load, LoginUser is the Login control
Page.Form.DefaultFocus = LoginUser.FindControl("Username").ClientID;
Related question: Set focus to textbox in ASP.NET Login control on page load

Related

Using TextBox TextChanged event to enable or disable a button control in asp.net

I am using an asp TextBox control with its TextChanged event and my goal is to capture text as a user enters it. If there are one or more characters entered, I would like a button control to be enabled without the user having to leave the TextBox control.
My source code for the TextBox on the aspx page is
<asp:TextBox ID="NewSpendingCategoryTextBox" MaxLength="12" runat="server"
AutoPostBack="True"
OnTextChanged="NewSpendingCategoryTextBox_TextChanged"
ViewStateMode="Enabled" >
</asp:TextBox>
and my source code on the code behind page is
Protected Sub NewSpendingCategoryTextBox_TextChanged(sender As Object, e As System.EventArgs) Handles NewSpendingCategoryTextBox.TextChanged
Dim strSpendingCategoryTextBox As String = Nothing
strSpendingCategoryTextBox = NewSpendingCategoryTextBox.Text
If strSpendingCategoryTextBox.Length <= 0 Then
Me.NewSpendingCategoryInsertButton.Enabled = False
Else 'strSpendingCategoryTextBox.Length > 0
Me.NewSpendingCategoryInsertButton.Enabled = True
End If 'strSpendingCategoryTextBox.Length <= 0
End Sub
So it appears I have to use javascript to enable or disable the insert button. Can someone guide me on how to get an element within a table? The table sits in a Panel as well.
below is the aspx code...
<asp:Panel ID="AddSpendingCategoryPanel" Visible="false" runat="server">
<table class="AddNewTable">
<tbody>
<tr>
<td>
<asp:Label ID="lblSpend" runat="server"
Text="Spending Category:">
</asp:Label>
</td>
<td>
<asp:TextBox ID="txtSpend" MaxLength="12"
runat="server"
AutoPostBack="True"
OnTextChanged="txtSpend_TextChanged"
OnKeyDown="return CheckSpendTextBoxValue()"
ViewStateMode="Enabled" >
</asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Button CssClass="frmbtn" ID="btnInsertSpend"
runat="server" Text="Insert" />
</td>
<td>
<asp:Button CssClass="frmbtn" ID="btnCancelSpend"
runat="server" Text="Cancel"
CausesValidation="False" />
</td>
</tr>
</tbody>
</table>
</asp:Panel>
Run this code in the OnKeyPress event or consider JavaScript. The textbox does not fire the Text_Changed event til Tab or Enter are used.
Simplify the boolean check.
Me.NewSpendingCategoryInsertButton.Enabled = (NewSpendingCategoryTextBox.Text.Length <> 0)
I'm not sure exactly how you would do it. But the ASP.NET code is executed on the server that is hosting the web page.
I'd highly recommended doing it on JavaScript which can be run client side. Hopefully this article is of use to you.
How to check if a textbox is empty using javascript

How can I retrieve the value of a control within an ASP.Net Dynamic Data Custom Field Template?

Long story short, for an old project I used ASP.Net Dynamic Data and probably did a terrible job with it. One of the Field Templates has multiple controls in it, and now I need to get at the value of one control from the FormView's Submit event because we changed the way that value is stored.
I can find the Field Template itself using FindFieldTemplate... but I can't figure out how to get to the controls inside of the template.
How can I do that without re-engineering the whole thing to pull that one field out? It would probably be more correct to re-engineer it, but this is a quick fix for a website that's going to be scrapped in a couple months.
EDIT: Was asked to show code so here it is. The FormView is pretty standard, just uses an . The Field Template actually has it's own listview and I'm controlling it's mode in codebehind. But I need to get the value of txtTitle.
Ticket_TicketMemo.ascx:
<asp:ListView ID="lvTicketMemos" DataSourceID="ldsTicketMemo"
InsertItemPosition="FirstItem" OnLoad="lvTicketMemo_Load" runat="server">
<LayoutTemplate>
<div style="overflow:auto; height:125px; width:600px;">
<table class="ListViewTable" runat="server">
<tr id="itemPlaceHolder" runat="server" />
</table>
</div>
</LayoutTemplate>
<ItemTemplate>
<tr valign="top" class='<%# Container.DataItemIndex % 2 == 0 ? "" : "Alternate" %>'>
<td><asp:DynamicControl ID="dcType" DataField="Type" runat="server" /></td>
<td><asp:DynamicControl ID="dcMemo" DataField="Memo" runat="server" /></td>
<td><asp:DynamicControl ID="dcCreateTime" DataField="CreateTime" runat="server" /></td>
</tr>
</ItemTemplate>
<InsertItemTemplate>
<tr valign="top">
<td colspan="3">
<asp:TextBox ID="txtTitle" Width="99%" Visible="false" OnLoad="txtTitle_Load" runat="server" /><br /><br />
</td>
</tr>
<tr valign="top">
<td colspan="3" width="600px">
<asp:TextBox ID="txtMemo" Text='<%# Bind("Memo") %>' Width="99%" OnLoad="txtMemo_Load" TextMode="MultiLine"
Rows="5" runat="server" />
<asp:RequiredFieldValidator ID="rfvMemo" Text="Must enter notes" ControlToValidate="txtMemo" runat="server" />
</td>
</tr>
</InsertItemTemplate>
I have just simulated your problem in my Dynamic Data project. Based on my research (and search) in order to get control value (not from DynamicControl value) in Dynamic Data you should implement the following method (i am using this method in my project and i have found one on Steve blog, i don't remember full link):
/// <summary>
/// Get the control by searching recursively for it.
/// </summary>
/// <param name="Root">The control to start the search at.</param>
/// <param name="Id">The ID of the control to find</param>
/// <returns>The control the was found or NULL if not found</returns>
public static Control FindControlRecursive(this Control Root, string Id)
{
if (Root.ClientID.IndexOf(Id) > 0)
return Root;
foreach (Control Ctl in Root.Controls)
{
Control FoundCtl = FindControlRecursive(Ctl, Id);
if (FoundCtl != null)
return FoundCtl;
}
return null;
}
Now, my EXAMPLE.
First, my custom Insert.aspx page with FormView and EntityDataSource:
<asp:FormView runat="server" ID="FormView1" DataSourceID="DetailsDataSource" DefaultMode="Insert"
OnItemCommand="FormView1_ItemCommand" RenderOuterTable="false">
<InsertItemTemplate>
<table>
<tr valign="top">
<td colspan="3">
<asp:TextBox ID="txtTitle" Width="99%" Visible="true" runat="server" /><br />
<br />
</td>
</tr>
</table>
</InsertItemTemplate>
</asp:FormView>
<asp:EntityDataSource ID="DetailsDataSource" runat="server" EnableInsert="true" OnInserted="DetailsDataSource_Inserted" />
Then, Inserted event of EntityDataSource:
protected MetaTable table;
protected void DetailsDataSource_Inserted(object sender, EntityDataSourceChangedEventArgs e)
{
if (e.Exception == null || e.ExceptionHandled)
{
string strTitle = String.Empty;
Control CtlTitle = FormView1.FindControlRecursive("txtTitle");
if (CtlTitle != null)
{
TextBox TextBoxTitle = (TextBox)CtlTitle;
strTitle = TextBoxTitle.Text;
}
Response.Redirect(table.ListActionPath + "?" + "Department_Id=" + strTitle);
}
}
Finally, i enter the text into txtTitle, for example, 13 and then i get

Custom CreateUserWizard

I'm using a CreateUserWizard control and I want to customize it to meet my requirements.
My question is: it possible using the CreateUserWizard control to move the Email textbox to another step then the CreateUserWizardStep step?
What I want to achieve is from the step #1 to have the UserName, Password and ConfirmPassword and on Step #2 the Email, a custom ConfirmEmail, SecurityQuestion/SecurityAnswer and other information.
I know how to add a wizard step but if I move any of the default textbox I'm getting an error about missing field in the CreateUserWizard step.
I suggest you to test with this structure
<asp:CreateUserWizard ID="CreateUserWizard1" runat="server" >
<WizardSteps>
<asp:CreateUserWizardStep runat="server">
.....
</asp:CreateUserWizardStep>
<asp:WizardStep runat="server">
...
</asp:WizardStep>
<asp:CompleteWizardStep runat="server" />
</WizardSteps>
</asp:CreateUserWizard>
Control of validating with ValidationGroup property, in order to activate validating just when needed
Link : http://msdn.microsoft.com/fr-fr/library/system.web.ui.webcontrols.button.validationgroup.aspx
After posting the question I start to try some alternative I havent think about. Like adding a WizardStep on top of the CreateUserWizard step where I have UserNameTextBox, PasswordTextBox and ConfirmPasswordTextBox.
The CreateUserWizard step contains a hiden UserName, Password and ConfirmPassword textbox which I set the values on ActiveStepChanged event. that step also contains the other required fields to create the user sich as Question and answer.
This meet my requirements and I am a happy programmer :)
Here I'm showing how to customized create user wizard & I'm using Microsoft Visual Studio Express 2013 For Web
In your register.aspx Page
<asp:CreateUserWizard ID="CreateUserWizard1" runat="server" OnCreatedUser="CreateUserWizard1_CreatedUser" CreateUserButtonText="Submit">
<WizardSteps>
<asp:CreateUserWizardStep ID="CreateUserWizardStep" runat="server">
<ContentTemplate>
<table>
<tr>
<td>User name:
</td>
<td>
<asp:TextBox ID="UserName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Password:
</td>
<td>
<asp:TextBox ID="Password" runat="server" TextMode="Password"></asp:TextBox></td>
</tr>
<tr>
<td>Confirm Password:</td>
<td><asp:TextBox ID="ConfirmPassword" runat="server" TextMode="Password"></asp:TextBox>
</td>
</tr>
<tr class="form-group">
<td>E-mail:
</td>
<td >
<asp:TextBox ID="Email" runat="server" TextMode="Email"></asp:TextBox>
</td>
</tr>
<tr>
<td>First Name:
</td>
<td>
<asp:TextBox ID="FirstName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Last Name:
</td>
<td>
<asp:TextBox ID="LastName" runat="server"></asp:TextBox>
</td>
</tr>
</table>
</ContentTemplate>
</asp:CreateUserWizardStep>
<asp:CompleteWizardStep runat="server"></asp:CompleteWizardStep>
</WizardSteps>
</asp:CreateUserWizard>
And CreateUserWizard1_CreatedUser code behind your Register.aspx.cs file use this code
var manager = new UserManager();
var user = new ApplicationUser() { UserName = CreateUserWizard1.UserName };
IdentityResult result = manager.Create(user, CreateUserWizard1.Password);
// Get the UserId of the just-added user
MembershipUser newUser = Membership.GetUser(CreateUserWizard1.UserName);
Guid newUserId = (Guid)newUser.ProviderUserKey;
//Get Profile Data Entered by user in Create User Wizard control
String FirstName = ((TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("FirstName")).Text;
String LastName = ((TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("LastName")).Text;
// Insert a new record into User_Profile
// Get your Connection String from the web.config. MembershipConnectionString is the name I have in my web.config
string connectionString = ConfigurationManager.ConnectionStrings["yourConnectionstring"].ConnectionString;
string insertSql = "INSERT INTO yourDBTableName(dbTcolumn,dbTcolumn, dbTcolumn) values(#dbTcolumn, #dbTcolumn)";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
IdentityHelper.SignIn(manager, user, isPersistent: false);
myConnection.Open();
SqlCommand myCommand = new SqlCommand(insertSql, myConnection);
myCommand.Parameters.AddWithValue("#dbTcolumn", FirstName);
myCommand.Parameters.AddWithValue("#dbTcolumn", LastName);
myCommand.Parameters.AddWithValue("#dbTcolumn", newUserId);
myCommand.ExecuteNonQuery();
myConnection.Close();
}
Here I'm not using RequiredFieldValidator. If you want to use, Just use Register.aspx page this bellow section
<asp:RequiredFieldValidator Display="Dynamic" ID="RequiredFieldValidator4" runat="server"
ControlToValidate="FirstName" ErrorMessage="The user name field is required." ValidationGroup="CreateUserWizard1"></asp:RequiredFieldValidator>
and add CreateUserWizard1_CreatedUser code behind if (result.Succeeded) in your Register.aspx.cs
I hope this is help to you customized your create user wizard.
Thanks

LoginView Control in ASP.NET 4.0

I want to access the text written in AnonymousTemplate of LoginView Control through Code behind.
You convert your the Login to visible template, and you must see something like:
<asp:Login ID="Login1" runat="server" >
<LayoutTemplate>
<table border="0" cellpadding="1" cellspacing="0" >
<tr>
<td>
...
<asp:TextBox ID="UserName" runat="server"></asp:TextBox>
....
then on code behind you find your control as:
TextBox TheUserName = (TextBox)Login1.FindControl("UserName");
where you place the correct user id, of your control that you wish to grab and change.

Enable/Disable table with javascript for multple instances on a single asp age

I just posted one question and got it answered very quickly, thank you.
I have a new problem, being I have a asp label which gets text dynamically set on it during instanation and then I have a onmousedown function tied to it call a javascript function to enable a table area that sitting below that is display - none by default. It all works fine until I put two of these user controls on a page. They both have the specificed label text correct but the javascript enable seems to set the display style attribute of the first usercontrol's table to block instead of the one that is sitting below the label that was clicked. I am sure this is because the script is running on the client side (which I really would like to keep) and all the user controls have the same id name (since they are all instaniations of the same user control) so the javascript to set the style display attribute just gets the first table. I can't seem to think of a good way to either dynamically name the table on instationation so i can specify this "uniquie" id name to the javascript or any other way to do this work.
the user control asp code is below:
function enableDivArea(objName) {
document.getElementById(objName).style.display = "block";
}
function disableDivArea(objName) {
document.getElementById(objName).style.display = "none";
document.forms[0].submit();
}<asp:Label style="cursor:pointer;color:#EA9156;font-family:Arial,Helvetica,sans-serif;font-weight:bold;" ID="m_emailAddressLabel" onmousedown="enableDivArea('EmailFormDivArea');" runat="server" Text="someone#emailaddress.com"></asp:Label>
<table id="EmailFormDivArea" style="display:none; border-style: outset; border-width: thin">
<tr>
<td>To: <asp:Label ID="m_sendEmailToLabel" runat="server" Text=""></asp:Label></td>
<td align="right"><asp:Label onmousedown="disableDivArea('EmailFormDivArea');" id="m_closeLabel" runat="server" Text="close"></asp:Label></td>
</tr>
<tr>
<td><asp:Label ID="m_fromLabel" runat="server" Text="First Name:" Visible="True"></asp:Label></td>
<td><asp:TextBox ID="m_firstNameBox" runat="server" Visible="True"></asp:TextBox></td>
</tr>
<tr>
<td><asp:Label ID="Label1" runat="server" Text="Last Name:" Visible="True"></asp:Label></td>
<td><asp:TextBox ID="m_lastNameBox" runat="server" Visible="True"></asp:TextBox></td>
</tr>
<tr>
<td><asp:Label ID="Label2" runat="server" Text="E-mail:" Visible="True"></asp:Label></td>
<td><asp:TextBox ID="m_emailBox" runat="server" Visible="True"></asp:TextBox></td>
</tr>
<tr>
<td><asp:Label ID="Label3" runat="server" Text="Phone number:" Visible="True"></asp:Label></td>
<td><asp:TextBox ID="m_phoneNumberBox" runat="server" Visible="True"></asp:TextBox></td>
</tr>
<tr>
<td><asp:Label ID="Label4" runat="server" Text="Message:" Visible="True"></asp:Label></td>
<td><asp:TextBox ID="m_messageBox" runat="server" Visible="True" Rows="6" TextMode="MultiLine"></asp:TextBox></td>
</tr>
<tr>
<td colspan="2" align="center"><asp:Button ID="m_sendMessageButton" runat="server" Text="Send Message"
onclick="m_sendMessageButton_Click" /></td>
</tr>
<tr>
<td colspan="2" align="center"><asp:Label runat="server" ID="m_statusLabel" Text="" Visible="true"></asp:Label></td>
</tr>
</table>
and the code behind looks like this:
protected void Page_Load(object sender, EventArgs e)
{
m_emailAddressLabel.Text = this.Parameter;
m_sendEmailToLabel.Text = this.Parameter;
}
Have the table runat server, and let the user control implement INamingContainer.
Construct the ID for the table, and set it programmatically (HtmlTable) in an overridden CreateChildControls, to for instance string.Concat(ID, "table").
EDIT: You also need dynamic ID references in the javascript.
You could use some <asp:PlaceHolder>'s for this, and then set this from code-behind in CreateChildControls,
but maybe it is just easier to move these small scripts inline, and emit scripts from code-behind,
setting client attributes on the asp:Label
Just a quick idea, do the tables both have the same ID? so the script only picks the first it finds?
make the ID unique!
use a asp:table and then
onmousedown="enableDivArea('<%=tableName.ClientID%>');"
First of all you can set the CssClass property for the style.
for hidding:
document.getElementById(theIdOfYourTable).style.display = 'none';
enabled goes the same
oops, I'm sorry, forgot that you can't use <%%> in a server tag (and doing this out of my head). Better for you would be to call the script like this:
onmousedown="enableDivArea(this);"
In your script you don't have to do document.getElementById anymore, since you get the element as a param already now.
I will keep that mind on the last reponse by Henk.
I acutally "cheated" in a new way with the help of your guys information. I dynamically added an attribute to the label that I wanted the javascript to run from the onmousedown from the Page_Load event and formatted the string how I wanted. Here is the line, it works fantastically (at least what I was looking for).
m_emailAddressLabel.Attributes.Add("onmousedown", "enableDivArea('" + EmailFormDivArea.ClientID + "');");
Thanks for all your help.

Resources