Custom CreateUserWizard - asp.net

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

Related

How do I dynamically create, and populate a Table (DataTable?)

The Issue I am currently facing is, I would like Keep the HMTL Table Structure I currently have, if at all possible.I would like tp dynamically create this table instead of doing so at the HTML level. I would Like to do so dynamically at the data level. Originally I had created a table via the ASPX page, and then I realized that I would have to go back and dynamically add in new revised row changes. This got ugly really quickly. my plan was to traverse each row in the table until i found the place I wanted to add a new row of data, but then I realized that it would mess up the columns to the right of the data, causing unwanted gaps if I added anything in the first 2 columns. I tried this code originally:
For Each row As HtmlTableRow In tblDates.Rows
For Each col As HtmlTableCell In tblDates.Columns
If col.ID = "lblSubmittedToESO" Then
tblDates.InnerHtml += "<tr> "
tblDates.InnerHtml += "<td> <asp:Label ID='lblSubmittedToESO' runat='server' Text='Date Site Plan Submitted to ESO for Approval: '></asp:Label></td>"
tblDates.InnerHtml += ""
tblDates.InnerHtml += ""
tblDates.InnerHtml += "</tr>"
End If
Next
Next
However, as you already know.. this did not work as there was no such thing as "tblDates.Columns". The original structure of my table is as follows:
<table id="tblDates" runat ="server" border="1">
<tr id ="tblDatesHeader">
<td>
</td>
<td align="center">
<asp:Label ID="lblDate" runat="server" Text="Date" Font-Bold="true"></asp:Label>
<br />
<asp:Label ID="lblDateFormat" runat="server" Text="(MM/DD/YYYY)" Font-Bold="true"></asp:Label>
</td>
<td colspan="2" align="center">
<asp:Label ID="lblNumOfDays" runat="server" Text="Number of Days to Complete Action"
Font-Bold="true"></asp:Label>
</td>
</tr>
<tr id ="ECOSubmitRow">
<td>
<asp:Label ID="lblSubmittedToECO" runat="server" Text="Date Site Plan Submitted to ECO for Approval: "></asp:Label>
</td>
<td>
<asp:TextBox ID="txtSubmittedToECO" runat="server"></asp:TextBox>
</td>
<td>
<asp:Label ID="lblPMO" runat="server" Text="PWO: "></asp:Label>
</td>
<td>
<asp:TextBox ID="txtPMO" runat="server"></asp:TextBox>
</td>
</tr>
<tr id ="ECOSignedRow">
<td>
<asp:Label ID="lblSignedByECO" runat="server" Text="Date Site Plan Signed by ECO: "></asp:Label> <img src="img/help_bubble.gif" id="helpbubble5" alt="" />
</td>
<td>
<asp:TextBox ID="txtSignedByECO" runat="server"></asp:TextBox>
</td>
<td>
<asp:Label ID="lblECO" runat="server" Text="ESO: "></asp:Label>
</td>
<td>
<asp:TextBox ID="txtECO" runat="server"></asp:TextBox>
</td>
</tr>
<tr id ="PMOSubmitRow">
<td>
<asp:Label ID="lblSubmittedToPMO" runat="server" Text="Date Site Plan Submitted to PMO for Approval: "></asp:Label>
</td>
<td>
<asp:TextBox ID="txtSubmittedToPMO" runat="server"></asp:TextBox>
</td>
<td>
<asp:Label ID="lblPMOECO" runat="server" Text="PMO/ECO sign to EED/MSC: "></asp:Label>
</td>
<td>
<asp:TextBox ID="txtPMOECO" runat="server"></asp:TextBox>
</td>
</tr>
<tr id ="PMOSignedRow">
<td>
<asp:Label ID="lblSignedByPMO" runat="server" Text="Date Site Plan Signed by PMO: "></asp:Label>
</td>
<td>
<asp:TextBox ID="txtSignedByPMO" runat="server"></asp:TextBox>
</td>
<td>
<asp:Label ID="lblEED" runat="server" Text="EED/MSC: "></asp:Label>
</td>
<td>
<asp:TextBox ID="txtEED" runat="server"></asp:TextBox>
</td>
</tr>
<tr id ="EEDSubmitRow">
<td>
<asp:Label ID="lblSubmittedToEED" runat="server" Text="Date Plan Submitted to EED for Endorsement: "></asp:Label>
</td>
<td>
<asp:TextBox ID="txtSubmittedToEED" runat="server"></asp:TextBox>
</td>
<td>
<asp:Label ID="lblABA" runat="server" Text="ABA: "></asp:Label>
</td>
<td>
<asp:TextBox ID="txtABA" runat="server"></asp:TextBox>
</td>
</tr>
<tr id ="EEDEndorcedRow">
<td>
<asp:Label ID="lblEndorsedByEED" runat="server" Text="Date Endorsed by EED/MSC and Forwarded to ABA: "></asp:Label>
</td>
<td>
<asp:TextBox ID="txtEndorsedByEED" runat="server"></asp:TextBox>
</td>
<td>
<asp:Label ID="lblOverallCycle" runat="server" Text="Project Overall Cycle Time: "></asp:Label>
</td>
<td>
<asp:TextBox ID="txtOverallCycle" runat="server"></asp:TextBox>
</td>
</tr>
<tr id ="ActionRow">
<td>
<asp:Label ID="lblABAaction" runat="server" Text="Date of ABA Action (Endorsement/Approval/Return): "></asp:Label>
</td>
<td>
<asp:TextBox ID="txtABAaction" runat="server"></asp:TextBox>
</td>
</tr>
<tr id ="InitDateRow">
<td>
<asp:Label ID="lblABAAAIInitDate" runat="server" Text="Inititial Date AAI was Issued: "></asp:Label>
</td>
<td>
<asp:TextBox ID="txtInitAAIDate" runat="server"></asp:TextBox>
</td>
</tr>
<tr id ="AAISubmitRow">
<td>
<asp:Label ID="lblAAISubmitted" runat="server" Text="Date Request Information Submitted: "></asp:Label>
</td>
<td>
<asp:TextBox ID="txtFIDate" runat="server"></asp:TextBox>
</td>
<td>
<asp:Label ID="lblFIDays" runat="server" Text="RFI Overall Days: "></asp:Label>
</td>
<td>
<asp:TextBox ID="txtRFITotal" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
<tr align="center">
<td colspan="2">
<asp:Label ID="lblRating" runat="server" Text="Rating (see note):" Font-Bold="true"></asp:Label>
</td>
<td>
<asp:Label ID="lblEEDEval" runat="server" Text="FEC or MCSC<br>Evaluation<br>Score: 0-100"
Font-Bold="true" Width="200px"></asp:Label>
</td>
<td>
<asp:Label ID="lblSSAEval" runat="server" Text="SSA<br>Evaluation<br>Score: 0-100"
Font-Bold="true"></asp:Label>
</td>
</tr>
<tr align="center">
<td colspan="2">
<asp:Label ID="lblOverall" runat="server" Text="Overall Score From Evaluation on Next Page:"></asp:Label>
</td>
<td align="center">
<asp:TextBox ID="txtFECOverall" runat="server" Width="40px"></asp:TextBox>
</td>
<td align="center">
<asp:TextBox ID="txtNossaOverall" runat="server" Width="40px"></asp:TextBox>
</td>
</tr>
</table>
So right now I have 4 stored procedures that pull dates for 4 different process. what I would like to is dynamically create this table and add the dates that I have already pulled and stored into objects and place them in this table in their specific position. Originally once I pulled the date I just added them in by referencing the "ID" of the . Normally it would be just adding a datasource and populating the table with that once source, but I would also like to design the layout. Attached to this question is a link for image to show what it looks like when I orginally created it. However, Now I would like to build it dynamically. Sample Table Output of Table Originally
Is there away to design the table this way, layout-wise?
Well, the issue (and difficult challenge) is that you thinking of a table in HTML and markup on the page. The problem is that 'table' as HTML is just markup, and as a result, REALLY difficult to work with.
So, what you want to do is at a conceptial level split out (seperate) your UI display of the table, and the the actual table you create in code.
So, think of the problem this way:
code + a table in memory.
HTML markup - display of the table.
So, once we split the two concepts?
Well, now you create that table, add rows to that table, maybe loop and sum a column on that table.
AND THEN display + render the results of that table.
Note the separation here. We have a data table. We do whatever we want with that table, AND THEN RENDER the table in HTML.
Note how we thus don't try to loop, try to modify, try to change the HTML table. (its too painful).
The other bonus? Well, in most cases we can assume you have a database. Thus, once again, the concept of the data, the data operations are 100% separate from what we going to display to the UI.
So, think data table operations. Do whatever.
THEN we render + display that table.
The above also means then we can use one of the "many" data repeating controls to do all the heavy lifting of the "display", but the code never really hits, touches, and attempts to modify the HTML - we only "render" the data AFTER we done our data operations.
if you break the above concept (data operations, and HMTL UI operations), then you have to start writing boatloads of code to try and update the HTML, but worse, the HTML is ONLY a representation of that internal data table anyway.
So, MUCH less work to do data operations, and when done, then just have asp.net do this:
Mr. asp.net, can you now just display my table for me? (especially after I done my data operations).
Since asp.net net can render + display that data table, and do so without looping or me having to write that code, then that's the approach I recommend.
my plan was to traverse each row in the table until i found the place I wanted to add a new row of data,
Caution!!!! - you don't really have a "place" in your data. You add a row of data to the system, and then query or pull or sort the data in the order you want. Data operations as a general rule does NOT have a order. You might have some invoice number, or some other column that you can (or want to) sort on, but again, thinking of data like old style punched cards in which order matters is a LESS then ideal way to think of data.
Your data is a bucket of rows. You do operations against that data, and THEN send it to the browser to be rendered as a table. Again, note the concept that we have data - a thing that is separate from display. As noted, we don't want to try and think of HTML as some table - it is ONLY for display - its only markup.
So, the first issue we deal with?
Where and how did this data come from in the first place? I mean, it rare as a cold day in hell that the data JUST appears out of now place. So, first up, is do you have, or are you using a database? (and note that since you NOT talked about that database system, this is the VERY reason why you are struggling here).
So, I can pick a repeater, GridView, ListView (my favorite), or many more controls that can display this data for you, but manipulation of the data? Nope - that occurs at the data level - not the UI level. Keep these two concepts separate.
So, where is this data coming from in the first place? Do you have this as a data table and database some place? I mean, you posted a screen shot of the data, but it can't just appear by magic, can it?
So, this is the first issue, first order of the day. Where is this data coming from? That's the first part of this puzzle. That data resides some place, and that is a good thing, but it not a HTML table - it is some data in a system that exists some place, and that is our starting point for this. Be this ms-access, FoxPro, Excel or some such?
that data comes from some place, and it exists. It would not make sense that every time we launch the program, that we re-type the data all over again. So, the where, the when, and the source of this data?
Note how you LEFT OUT this detail!!!! - and that's why we are struggling here!
So, say I have a table with some hotels. Well, then I can render (display) the data as some type of HTML table - and might as well let asp.net do that dirty work for us.
So, say we have this markup. In fact, I used the wizard, AND THEN blew out the sql data source that gets placed on the page (I want more control over the data with code).
So, say we have this markup:
<div id="MyGrid" runat="server" style="width:40%">
<asp:Button ID="cmdAdd" runat="server" Text="+Add New" CssClass="btn" />
<asp:GridView ID="GHotels" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" CssClass="table">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:Button ID="cmdEdit" runat="server" Text="Edit" CssClass="btn"
OnClick="cmdEdit_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
</div>
So, I dropped in a grid view. (but, with your sample markup, a listView probably is better).
Now, we have this code to load up the above:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadGrid()
End If
End Sub
Sub LoadGrid()
Dim cmdSQL As New SqlCommand("SELECT * FROM tblHotelsA ORDER BY HotelName")
Dim rstData as DataTable = MyrstP(cmdSQL)
GHotels.DataSource = rstData
GHotels.DataBind()
End Sub
Public Function MyrstP(sqlCmd As SqlCommand) As DataTable
Dim rstData As New DataTable
Using sqlCmd
Using conn = New SqlConnection(My.Settings.TEST4)
conn.Open()
sqlCmd.Connection = conn
rstData.Load(sqlCmd.ExecuteReader)
End Using
End Using
Return rstData
End Function
Ok, and now we have this:
Note careful:
We did not write loops to load up the HTML.
We use the ado.net data table to get the data. And THEN SEND that data table to the HTML system to display.
Note how we NOT directly working with the HMTL - since well, it is JUST HTML, and as NO business try to be a data system for us - but is great for display!
So, in above, we have a add new button at the top. That could allow us to add a new row to the data base. But, once again, we would add the new row, and then AGAIN send that data (and our new row) to the Gridview, but AGAIN we don't write HTML, we don't try to modify the HTML, and we still have 100% data operations.
Now, no question we might need some markup to edit a single row. That markup to edit ONE row can then be used for our "edit" button, and even our add new button.
So, markup can be used for data entery, but for display of the table and data? That goes and belongs in the database.
So, in above, we might below the grid, drop in some markup that allows edit of one row.
Say, like this:
<div id="EditRecord" runat="server" style="float:left;display: normal" clientidmode="Static" >
<style>
.iForm label {display:inline-block;width:90px}
.iForm input {border-radius:8px;border-width:1px;margin-bottom:10px}
.iForm textarea {border-radius:8px;border-width:1px;margin-bottom:10px}
.iForm input[type=checkbox] {margin-right:8px}
</style>
<div style="float:left" class="iForm">
<label>HotelName</label><asp:TextBox ID="txtHotel" runat="server" f="HOtelName" width="280"></asp:TextBox> <br />
<label>First Name</label><asp:TextBox ID="tFN" runat="server" f="FirstName" Width="140"></asp:TextBox> <br />
<label>Last Name</label><asp:TextBox ID="tLN" runat="server" f="LastName" Width="140"></asp:TextBox> <br />
<label>City</label><asp:TextBox ID="tCity" runat="server" f="City" Width="140"></asp:TextBox> <br />
<label>Province</label><asp:TextBox ID="tProvince" runat="server" f="Province" Width="75"></asp:TextBox> <br />
</div>
<div style="float:left;margin-left:20px" class="iForm">
<label>Description</label> <br />
<asp:TextBox ID="txtNotes" runat="server" Width="400" TextMode="MultiLine"
Height="150px" f="Description" ></asp:TextBox> <br />
<asp:CheckBox ID="chkActive" f="Active" Text=" Active" runat="server" TextAlign="Right" />
<asp:CheckBox ID="chkBalcony" f="Balcony" Text=" Has Balcony" runat="server" TextAlign="Right" />
</div>
<div style="clear:both"></div>
<button id="cmdSave" runat="server" class="btn" onserverclick="cmdSave_ServerClick" >
<span aria-hidden="true" class="glyphicon glyphicon-floppy-saved"> Save</span>
</button>
<button id="cmdCancel" runat="server" class="btn" style="margin-left:15px"
onserverclick="cmdCancel_ServerClick"
>
<span aria-hidden="true" class="glyphicon glyphicon-arrow-left"> Back/Cancel</span>
</button>
<button id="cmdDelete" runat="server" class="btn" style="margin-left:15px">
<span aria-hidden="true" class="glyphicon glyphicon-trash"> Delete</span>
</button>
</div>
So, that is some markup, and then we have tht button click for each row.
Our code for that click can look like this:
Protected Sub cmdEdit_Click(sender As Object, e As EventArgs)
Dim btn As Button = sender
Dim gRow As GridViewRow = btn.NamingContainer
Dim pkID = GHotels.DataKeys(gRow.RowIndex).Item("ID")
Dim cmdSQL As New SqlCommand("SELECT * from tblHotelsA where ID = #ID")
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = pkID
Dim rstData As DataTable = MyrstP(cmdSQL)
Call fLoader(Me.EditRecord, rstData.Rows(0)) ' load up hidden div with data
' hide grid
MyGrid.Style.Add("display", "none")
EditRecord.Style.Add("display", "normal")
ViewState("rstData") = rstData
End Sub
Again, note how we do data operations against the database - NOT the HTML table!!! - we certainly did use the "UI" and row click of the grid to get that one row to work on, but after that we RIGHT BACK to useing datatable, and data operations against the database and NOT AGAINST the HTML markup.
So, when you click on a row, we get the row "PK" data id, pull the data, load up some controls on the page, hide the grid, show the "div" that has above. We now get this:
Now, this post is already a bit long, and I could post more code. So, in above, the save button would:
Send data back to database (again, database - not touch the grid view or "table"
Then we re-load the grid view from database
Then we hide our div to edit, and show the div with the grid view to display any edits we made.
this code:
Protected Sub cmdSave_ServerClick(sender As Object, e As EventArgs)
Dim rstData As DataTable = ViewState("rstData")
Call fWriterW(EditRecord, rstData.Rows(0)) ' div to table
Call SaveTable(rstData, "tblHotelsA") ' send table back to database
LoadGrid() ' refresh grid
MyGrid.Style.Add("display", "normal")
EditRecord.Style.Add("display", "none")
End Sub
So, the FIRST question we have and need to know here?
Where is your data now, how do you plan to load + read this data. This is the first step, and worry about some HTML markup to display that data actually is the easy part - but the source and getting that data - now that's the important part of this question and process.
I should note that I come from a ms-access, VB6, FoxPro background (desktop). So, you note the above style of code - looks a lot like VBA due to my roots. But, I did make + build a few helper routines used above, (like fLoader, fWirter) that makes such code easy to write.
So, your first issue? Where does the data come from now, and have you setup a valid connection and means to pull that data into a "data table", of which we THEN can send to the browser as HTML.
Edit -- I see you note that you have 4 store procedures. So yes then you can pull that data to a datatable, and then send that datatable to a GridView or say a listview.
In fact, given your existing markup, then I would suggest a listview. As noted, I often use the wizard to build the listview (or gridview). I then blow out (delete) the sql data source that the wizard creates, and as noted, removed the extra templates.
So, you have a table layout that would work quite well as a ListView.
So, taking your existing markup, say this:
It will look somthing like this:
<div style="width:60%;padding:25px">
<asp:ListView ID="ListView1" runat="server" DataKeyNames="ID" >
<LayoutTemplate>
<table id="itemPlaceholderContainer" runat="server" border="0" class="table table-hover table-bordered" >
<tr runat="server" style="">
<th runat="server">Site Plan</th>
<th runat="server" style="text-align:center">Date<br />(MM/DD/YYYY)</th>
<th runat="server" colspan="2">Number of Days to Complete Action</th>
<th runat="server">PWO</th>
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr id ="ECOSubmitRow">
<td>
<asp:Label ID="lblSubmittedToECO" runat="server" Text="Site Plan Submitted to ECO for Approval: "></asp:Label>
</td>
<td>
<asp:Label ID="PlanDate" runat="server" Text="MM/DD/YYYY"></asp:Label>
</td>
<td>
<asp:Label ID="lblPMO" runat="server" Text="PWO: "></asp:Label>
</td>
<td>
<asp:TextBox ID="txtPMO" runat="server"></asp:TextBox>
</td>
</tr>
</ItemTemplate>
</asp:ListView>
So, we have kind of this now:
and in fact, for the actual data, we only need ONE row.
so, looking at this, note how I suggested a list view.
I don't have your data - so, I can't really do a lot in a simple post on SO but lets re-create the first hotel grid, but using the List view.
Note how the layout is "very" simular to a table.
So, for the Hotel grid, using a ListView, then we have this:
<asp:ListView ID="ListView1" runat="server" DataKeyNames="ID" >
<LayoutTemplate>
<table id="itemPlaceholderContainer" runat="server" border="0" class="table table-bordered">
<tr runat="server" style="">
<th runat="server">FirstName</th>
<th runat="server">LastName</th>
<th runat="server">HotelName</th>
<th runat="server">Active</th>
<th runat="server">Description</th>
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr style="">
<td><asp:Label ID="FirstNameLabel" runat="server" Text='<%# Eval("FirstName") %>' /></td>
<td><asp:Label ID="LastNameLabel" runat="server" Text='<%# Eval("LastName") %>' /></td>
<td><asp:Label ID="HotelNameLabel" runat="server" Text='<%# Eval("HotelName") %>' /></td>
<td style="text-align:center">
<asp:CheckBox ID="ActiveCheckBox" runat="server" Checked='<%# Eval("Active") %>' />
</td>
<td><asp:Label ID="DescriptionLabel" runat="server" Text='<%# Eval("Description") %>' /></td>
</tr>
</ItemTemplate>
</asp:ListView>
Note again, VERY simular to a HTML table, but we use ListView, since it is like GridView a data bound control. And we can then feed it that data table.
So, my code to load this list view, is this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadGrid
End If
End Sub
Sub LoadGrid()
Dim cmdSQL = New SqlCommand("SELECT * FROM tblHotelsA ORDER BY HotelName")
Dim rstData As DataTable
rstData = MyrstP(cmdSQL)
ListView1.DataSource = rstData
ListView1.DataBind()
End Sub
And I get this:
So, while the GridView is "quick and dirty" as you layout becomes a little more complex, then ListView becomes a better choice - and its layout VERY much follows a HTML table, but the big deal is of course that you can feed it a data table - so, we don't try to create the HTML table or markup - we setup a layout, and feed it that data table.

Trigger confirmation message box during asp.net LoggingIn event

I have a web application in vb in which I am using this approach to prevent a user from having concurrent logins due to a simple licensing agreement.
It works great, if a user logs in with an account that is already in use, the first user gets logged out. I am trying to add a messagebox or some kind of js confirmation box in the loggingin event that states:
This user account has been active in the last 20 minutes.
If someone else is using it, then logging in may possibly
compromise any report generation or activity.
Continue login?
Here is the code:
<asp:Login ID="Login1" runat="server" DestinationPageUrl="~/Dashboard/Default.aspx" >
<LayoutTemplate>
<table border="0" cellpadding="0">
<tr>
<td align="right"><p><asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">User Name:</asp:Label></p></td>
<td align="right">
<p><asp:TextBox ID="UserName" runat="server" Width="220" autocomplete="on" />
<asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="UserName" Text="*"
ErrorMessage="User Name is required." ToolTip="User Name is required." ValidationGroup="Login1" /></p>
</td>
</tr>
<tr>
<td align="right"><p><asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label></p></td>
<td align="right">
<p><asp:TextBox ID="Password" runat="server" TextMode="Password" Width="220"></asp:TextBox>
<asp:RequiredFieldValidator ID="PasswordRequired" runat="server" ControlToValidate="Password" Text="*"
ErrorMessage="Password is required." ToolTip="Password is required." ValidationGroup="Login1" /></p>
</td>
</tr>
<tr>
<td align="center" colspan="2" style="color: red"><asp:Literal ID="FailureText" runat="server" EnableViewState="False"></asp:Literal></td>
</tr>
<tr>
<td align="right" colspan="2"><asp:LinkButton CssClass="prettyButton" ID="LoginButton" runat="server" CommandName="Login" Text="Log In" ValidationGroup="Login1" /></td>
</tr>
</table>
</LayoutTemplate>
</asp:Login>
Private Sub Login1_LoggingIn(sender As Object, e As LoginCancelEventArgs) Handles Login1.LoggingIn
Dim messagetext As String = "This user account has been active in the last 20 minutes." + Environment.NewLine + Environment.NewLine
messagetext += "If someone else is using it, then logging in may possibly" + Environment.NewLine
messagetext += "compromise any report generation or activity." + Environment.NewLine + Environment.NewLine
messagetext += "Continue login?"
Dim userNameTextBox As System.Web.UI.WebControls.TextBox = DirectCast(Login1.FindControl("UserName"), System.Web.UI.WebControls.TextBox)
Dim currentUser As MembershipUser = Membership.GetUser(userNameTextBox.Text)
If currentUser IsNot Nothing Then
If currentUser.IsOnline Then
'*****CONFIRMATION MESSAGE BOX TO GO HERE*****/
Dim result = MessageBox.Show(messagetext , "Login Warning", MessageBoxButtons.YesNo)
'* IF USER DECIDES NOT TO LOGIN:*/
If result = DialogResult.No Then
e.Cancel = True
End If
'* ELSE LOGIN CONTINUES AND ORIGINAL USER IS LOGGED OUT*/
End If
End If
End Sub
Private Sub Login1_LoggedIn(sender As Object, e As EventArgs) Handles Login1.LoggedIn
Dim userNameTextBox As System.Web.UI.WebControls.TextBox = DirectCast(Login1.FindControl("UserName"), System.Web.UI.WebControls.TextBox)
SingleSessionPreparation.CreateAndStoreSessionToken(userNameTextBox.Text)
End Sub
Now, I can use a windows form msgbox() locally, and everything works great, but once I put it on a server, the message box obviously doesn't work. I've tried ClientScript and ScriptManager, but the client side check doesn't seem to get triggered.
Any help is greatly appreciated.
Do not use the VB MessageBox in a web site. It will ONLY show up on the server - and will more than likely kill your page every time. The end user will never see it on his browser.
There are a bunch of ways you could handle what you're trying to achieve, though one that will work well is to show the user a javascript confirm box; which is more or less the same as a message box but has an OK and Cancel button instead.
You can show this to the user by injecting a little javascript to your page as it renders. So, remove your Dim result.... line and replace it with something like this: - this will inject some javascript to your pages HTML.
Dim cs As ClientScriptManager = Page.ClientScript
cs.RegisterStartupScript(Me.GetType(), "userChecker", "UserCheck(Confirm('yourMessage'));", True)
NOTE - you will also remove the code that checks your dialog, I.E If result = ....
When the page loads the confirm dialog will appear. The captured response, in this case, will be passed to a javascript function called UserCheck - so have a javascript function in your HTML to accept it. Something like this:
function UserCheck(t){
if (t){
// do something for OK
}else{
// do something for CANCEL
}
Within the UserCheck you can easily handle the users response. Perhaps by redirecting, or causing a postback by calling the __doPostBack function of .Net.

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

GridView isn't reflecting AJAX changes

I'm using AJAX right now to update my GridView when I search for a string of text in the gridview, or when I select from a dropdownlist what I want to order the Gridview by. This was working previously, but I had really messy code. So I've cleaned it up a little bit, added some parameters and such. Unfortunately, now, when the selectedindex of the dropdownlist is changed or when someone tries to search for a field, nothing happens - the page just refreshes. I'm also getting an exception saying "The SELECT item identified by the ORDER BY number 1 contains a variable as part of the expression identifying a column position. Variables are only allowed when ordering by an expression referencing a column name".
If you need to see any more code then please let me know!
public vieworders()
{
this.PreInit += new EventHandler(vieworders_PreInit);
}
void vieworders_PreInit(object sender, EventArgs e)
{
orderByString = orderByList.SelectedItem.Value;
fieldString = searchTextBox.Text;
updateDatabase(fieldString, orderByString);
}
protected void updateDatabase(string _searchString, string _orderByString)
{
string updateCommand = "SELECT fName,lName,zip,email,cwaSource,price,length FROM SecureOrders WHERE fName LIKE #searchString OR lName LIKE #searchString OR zip LIKE #searchString OR email LIKE #searchString OR cwaSource LIKE #searchString OR length LIKE #searchString OR price LIKE #searchString ORDER BY #orderByString";
Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Cabot3");
ConnectionStringSettings connectionString = rootWebConfig.ConnectionStrings.ConnectionStrings["secureodb"];
// Create an SqlConnection to the database.
using (SqlConnection connection = new SqlConnection(connectionString.ToString()))
using (SqlCommand _fillDatabase = new SqlCommand(updateCommand, connection))
{
connection.Open();
_fillDatabase.Parameters.Add("#searchString", SqlDbType.VarChar, 50).Value = _searchString;
_fillDatabase.Parameters.Add("#orderByString", SqlDbType.VarChar, 50).Value = _orderByString;
_fillDatabase.ExecuteNonQuery();
dataAdapter = new SqlDataAdapter("SELECT * FROM SecureOrders", connection);
// create the DataSet
dataSet = new DataSet();
// fill the DataSet using our DataAdapter
dataAdapter.Fill(dataSet, "SecureOrders");
DataView source = new DataView(dataSet.Tables[0]);
DefaultGrid.DataSource = source;
DefaultGrid.DataBind();
connection.Close();
}
}
Form
<form id="form1" runat="server">
<asp:ScriptManager ID = "ScriptManager" runat="server" />
<div>
<asp:Label runat="server" id = "orderByLabel" Text = "Order By: " />
<asp:DropDownList runat="server" ID="orderByList" AutoPostBack="true">
<asp:ListItem Value="fName" Selected="True">First Name</asp:ListItem>
<asp:ListItem Value="lName">Last Name</asp:ListItem>
<asp:ListItem Value="state">State</asp:ListItem>
<asp:ListItem Value="zip">Zip Code</asp:ListItem>
<asp:ListItem Value="cwaSource">Source</asp:ListItem>
<asp:ListItem Value="cwaJoined">Date Joined</asp:ListItem>
</asp:DropDownList>
</div>
<div>
<asp:Label runat="server" ID="searchLabel" Text="Search For: " />
<asp:TextBox ID="searchTextBox" runat="server" Columns="30" />
<asp:Button ID="searchButton" runat="server" Text="Search" />
</div>
<div>
<asp:UpdatePanel ID = "up" runat="server">
<ContentTemplate>
<div style= "overflow:auto; height:50%; width:100%">
<asp:GridView ID="DefaultGrid" runat = "server" DataKeyNames = "IdentityColumn"
onselectedindexchanged = "DefaultGrid_SelectedIndexChanged"
autogenerateselectbutton = "true">
<SelectedRowStyle BackColor="Azure"
forecolor="Black"
font-bold="true" />
<Columns>
<asp:TemplateField HeaderText="Processed">
<ItemTemplate>
<asp:CheckBox ID="CheckBoxProcess" AutoPostBack = "true" Checked ='<%#Eval("processed") %>' OnCheckedChanged="CheckBoxProcess_CheckedChanged" runat="server" Enabled="true" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</div>
<div style= "overflow:auto; height:50%; width:100%" />
<table border="1">
<tr>
<td>Name: </td>
<td><%=name %></td>
</tr>
<tr>
<td>Zip: </td>
<td><%=zip %></td>
</tr>
<tr>
<td>Email: </td>
<td><%=email %></td>
</tr>
<tr>
<td>Length: </td>
<td><%=length %></td>
</tr>
<tr>
<td>Price: </td>
<td><%=price %></td>
</tr>
<tr>
<td>Source: </td>
<td><%=source %></td>
</tr>
</table>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
I have never used the UpdatePanel since my company uses Telerik, but from the examples I see during my research I remember seeing a trigger component.
From my understanding, if the control is w/i the UpdatePanel itself, then you do not have to specify the trigger, since it is assumed.
For your scenario, the trigger (dropdownlist) is outside of the UpdatePanel. You may need to include this in your aspx:
<asp:UpdatePanel ID = "up" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="orderByList" >
</Triggers>
<ContentTemplate>
...
Try the following:
In HTML move the update panel direct after the scriptmanager line.
Move the code lines in vieworders_PreInit to vieworders_PageLoad with !IsPostPack clause.

how to set the focus to a control by default?

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

Resources