Since being new to .NET i am having difficiltues in connecting my VS 2013 with SQL.
I have already connected it with the DB but now i want to know how can i insert data in my AdventureWork Databaze, from a text box that is in my page. Can you please help me cuz really im not getting it
Below you can find some of my code:
<h1>Add in Database</h1>
<div>
Enter Name: <asp:TextBox ID="TextBox3" runat="server" ></asp:TextBox>
</br></br>
</div>
Enter Surname: <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
</br></br>
Gender: <asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>
<br />
<br />
<asp:Label ID="Label1" runat="server" ForeColor="#CC3300" Text="Label"></asp:Label>
</br></br>
<asp:Button ID="Button2" runat="server" Text="Submit" OnClick="Button1_Click" />
<asp:SqlDataSource ID="SqlDataSource2" runat="server">
ConnectionString="<$ ConnectionStrings:AdventureWorks2014ConnectionString >"
SelectCommand="INSERT INTO [users] VALUE ([FirstName] = #FirstName)" ProviderName="System.Data.SqlClient">
</asp:SqlDataSource>
<br />
<br />
<br />
</form>
and: `
protected void Button2_Click(object sender, EventArgs e)
{
SqlConnection cnn = new SqlConnection();
cnn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["AdventureWorks2014ConnectionString"].ConnectionString;
cnn.Open();
SqlCommand cmd = new SqlCommand("Insert into users (FirstName,LastName,Gender) Values (#Name,#Surname,#Gender)",cnn);
cmd.Parameters.AddWithValue("#Name", TextBox3.Text);
cmd.Parameters.AddWithValue("#Surname", TextBox4.Text);
cmd.Parameters.AddWithValue("#Gender", TextBox5.Text);
cnn.Open();
cmd.ExecuteNonQuery();
cnn.Close();
if (IsPostBack)
{
TextBox3.Text = "";
TextBox4.Text = "";
TextBox5.Text = "";
}
}
While I am unsure why the code above is not working. I have duplicated this and rewritten the button click handler code. Here is my working sample below:
protected void Button2_Click(object sender, EventArgs e)
{
var connStr = ConfigurationManager.ConnectionStrings["AdventureWorks2014ConnectionString"].ConnectionString;
using (var cnn = new SqlConnection(connStr)) {
cnn.Open();
var cmd = cnn.CreateCommand();
cmd.CommandText = "Insert into users (FirstName,LastName,Gender) Values (#Name,#Surname,#Gender)";
cmd.Parameters.AddWithValue("#Name", TextBox3.Text);
cmd.Parameters.AddWithValue("#Surname", TextBox4.Text);
cmd.Parameters.AddWithValue("#Gender", TextBox5.Text);
var affectedRows = cmd.ExecuteNonQuery();
// Do validation here.
// This should be 1, the number of rows inserted.
}
if (IsPostBack)
TextBox3.Text = TextBox4.Text = TextBox5.Text = string.Empty;
}
I noticed that in your sample you are attempting to open the database connection twice. Other corrections you could make would be to wrap your SqlConnection in a using statement. In that way when the object disposes, it will close the connection for you. Also check the resulting number of rows affected coming back from the insert statement. This may give you some clue as to why the data is not inserted. If you are using SQL Server Developer Edition, you can start the SQL Profiler to see the resulting T-SQL statement being sent from your application to the SQL Server. I hope this helps.
Related
I am developing an asp.net page with two DropDown List populating values from the same table in the Database where a user is required to select account name and I would like the second DropDown List to automatically populates it's own values (Acount Code) sharing the same Account name based on the First dropdown list selection. Here is my sample code ...
<span class="label">
<asp:Label ID="Label2" runat="server" Text="Account Name"</asp:Label>
</span>
<asp:DropDownList ID="name" runat="server"></asp:DropDownList><br />
<span class="label">
<asp:Label ID="Label3" runat="server" Text="Account Code"></asp:Label>
</span>
<asp:DropDownList ID="code" runat="server"></asp:DropDownList>
and my C# code is as follow ..
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string CS = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
using (SqlConnection conn = new SqlConnection(CS))
{
SqlCommand comm = new SqlCommand("SELECT AccountName, AccountCode FROM Account", conn);
conn.Open();
name.DataSource = comm.ExecuteReader();
name.DataTextField = "AccountName";
name.DataValueField = "AccountName";
name.DataBind();
conn.Close();
if(name.Text != null)
{
conn.Open();
SqlCommand com = new SqlCommand("SELECT AccountCode FROM Account WHERE AccountName= '" + name.Text +"'", conn);
code.DataSource = com.ExecuteReader();
code.DataTextField = "AccountCode ";
code.DataValueField = "AccountCode ";
code.DataBind();
}
}
}
}
In my case if i Change the Values of Account Name, the Account Code does not change automatically. How can i make that happen ..? Thank you
to meet your requirements you will have to add two attributes to your first drop down (1) "AutoPostBack" and (2) "OnSelectedIndexChanged".
1) Autopostback will cause a postback when you select an item in the dropdown.
2) OnSelectedIndexChanged is an event you will have to code to fill the second dropdown.
<asp:DropDownList ID="name" runat="server" AutoPostBack="true" OnSelectedIndexChanged="name_SelectedIndexChanged"></asp:DropDownList>
I am programming in ASP.NET, visual studio. I have a dropdown list created in HTML form. If I dropdown the list, it displays the record from associated column in the table. But what I want is to show the corresponding value / record with that list item.
For example in the table, I have column id, productname and price. After choosing a particular product name (from drop down list), the associated price with it must be displayed in front of it (in a label).
However, By default, I want the drop down list to shows nothing in the beginning.
UPDATE:
Store.aspx:
<form id="form1" runat="server">
<div>
Welcome
<asp:Label ID="Label3" runat="server" ></asp:Label>
<br />
<br />
Products: <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" ></asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [productdata]"></asp:SqlDataSource>
Price:
<asp:Label ID="Label1" runat="server" ></asp:Label>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Add to Cart" />
<br />
<br />
Items in cart: <asp:DropDownList ID="DropDownList2" runat="server"></asp:DropDownList>
<br />
<br />
Total Price: <asp:Label ID="Label2" runat="server"></asp:Label>
</div>
</form>
Store.aspx.cs:
public partial class Store : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Label3.Text = Request.QueryString["name"];//show welcome text
String cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
if (!IsPostBack)
{
using (SqlConnection sc = new SqlConnection(cs))
{
SqlCommand sqlcom = new SqlCommand("Select id, productname, price from productdata", sc);
sc.Open();
DropDownList1.DataTextField = "productname";//show in the dropdown list
DropDownList1.DataValueField = "price"; //show in the label
DropDownList1.DataSource = sqlcom.ExecuteReader();
DropDownList1.DataBind();
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
String cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlDataReader rd;
using (SqlConnection sc = new SqlConnection(cs))
{
SqlCommand sqlcom = new SqlCommand("Select id, productname, price from productdata where id=" + Convert.ToUInt32(DropDownList1.SelectedValue), sc);
sc.Open();
rd = sqlcom.ExecuteReader();
if (rd.Read())
{
Label1.Text = rd[2].ToString();
}
sc.Close();
}
}
}
Database:
CREATE TABLE [dbo].[productdata] (
[Id] INT NOT NULL,
[productname] VARCHAR (50) NULL,
[price] FLOAT (53) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
This Edit according to using AutoPostBack=True and if (!IsPostBack) in Page_Load thanks to Arindam:
For simply solution using postback event:
First you should add OnSelectedIndexChanged event for dropdownlist
<asp:DropDownList ID="DropDownList1" runat="server"
OnSelectedIndexChanged="GetPrice" AutoPostBack="true">
</asp:DropDownList>
Then in code behind you just get selected value and fill to the label price
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Label3.Text = Request.QueryString["name"];//show welcome text
String cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection sc = new SqlConnection(cs))
{
SqlCommand sqlcom = new SqlCommand("Select id, productname, price from productdata", sc);
sc.Open();
DropDownList1.DataTextField = "productname";//show in the dropdown list
DropDownList1.DataValueField = "price"; //show in the label
DropDownList1.DataSource = sqlcom.ExecuteReader();
DropDownList1.DataBind();
}
}
}
protected void GetPrice(object sender, EventArgs e)
{
Label1.Text = DropDownList1.SelectedValue;
}
You have to use AutoPostBack=True so that when you change index of dropdownlist, it will trigger a postback to server so the function GetPrice(...) will be called.
Every time the page postback, it will call function Page_Load(...) first, so you must use propertive IsPostBack to check if case1_this is the first time the page is loaded, or case2_a postback event, and you only set the ddl datasource at case1 because if you set datasource, by default the dropdownlist will reset to select first item in list.
When you go advance, you should consider using Javascript and Jquery to solve this, so the page will not load again like this postback solution.
And one more thing, you should name your controls well, don't make them default like that. It's one of two hard things in programming.
Yes you can but if not please use datatable and i am sure that work fine .if u not able do that just post I will give the correction.
I am working on a small search form that has two text fields: One that allows users to search for a job list (which is basically a wish list--don't know why they want to call it a "job list" but whatever) by entering in part of or a full email address or someone's first and/or last name (This textbox is called SearchName). This field is required and if it is blank when the user hits "Search," an error message appears telling them so. The second textbox is optional, and it allows users to enter in a city or a state to help narrow their search down even more (this textbox is called SearchLocation).
I have a function (called getJobLists()) that is used by the search button to get results.
As it is right now, the part of the function that returns results based on what is entered into the SearchName field works perfectly. However, I cannot get any results for SearchLocation. When I enter a valid email or name into SearchName, then enter a valid city or state into SearchLocation, I get no results. However, if I enter in anything invalid (i.e. a city that is not associated with the entered email or name) the "no results found" message does appear.
I have tested both SQL queries in my search function in SQL Server Management Studio and they do work perfectly.
I have a try-catch inside the search function, but no error is being shown, not even in the console.
This is the code behind:
protected void Page_Load(object sender, System.EventArgs e)
{
// CHECK IF THE WISHLIST SEARCH ENABLED
StoreSettingsManager settings = AbleContext.Current.Store.Settings;
if (!settings.WishlistSearchEnabled)
{
Response.Redirect(AbleCommerce.Code.NavigationHelper.GetHomeUrl());
return;
}
}
protected void getJobLists()
{
try
{
if (SearchName.Text != "")
{//if SearchName.Text is not blank
if (SearchLocation.Text != "")
{//check to see if SearchLocation.Text is not blank either
string sqlSelect = "SELECT (FirstName +' '+ LastName) AS 'FullName', UserName, (Address1 + ', ' +City + ', ' + Province) AS 'Address' FROM ac_Users INNER JOIN ac_Wishlists ON ac_Wishlists.UserId = ac_Users.UserId INNER JOIN ac_Addresses ON ac_Addresses.UserId = ac_Wishlists.UserId WHERE IsBilling ='true' AND (UserName LIKE '%'+#UserName+'%' OR (FirstName + LastName) LIKE '%'+#UserName+'%') AND ((City + Province) LIKE '%'+#Location+'%')";
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
{
SqlCommand cmd = new SqlCommand(sqlSelect, cn);
cmd.Parameters.AddWithValue("#UserName", String.Format("%{0}%", SearchName.Text));
cmd.Parameters.AddWithValue("#Location", String.Format("%{0}%", SearchLocation.Text));
cmd.CommandType = CommandType.Text;
cn.Open();
DataSet ds = new DataSet();
DataTable jobsListsTbl = ds.Tables.Add("jobsListsTbl");
jobsListsTbl.Columns.Add("User", Type.GetType("System.String"));
jobsListsTbl.Columns.Add("PrimaryAddress", Type.GetType("System.String"));
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
DataRow dr = jobsListsTbl.NewRow();
dr["User"] = reader["Name"];
dr["PrimaryAddress"] = reader["Address"];
jobsListsTbl.Rows.Add(dr);
}
}
WishlistGrid.DataSource = ds;
WishlistGrid.DataMember = "jobsListsTbl";
WishlistGrid.DataBind();
}
}//end of if(SearchLocation.Text !='')
else
{//if SearchLocation.Text is blank, then go with this code instead
string sqlSelect2 = "SELECT (FirstName +' '+ LastName) AS 'FullName', UserName, (Address1 + ', ' +City + ', ' + Province) AS 'Address' FROM ac_Users INNER JOIN ac_Wishlists ON ac_Wishlists.UserId = ac_Users.UserId INNER JOIN ac_Addresses ON ac_Addresses.UserId = ac_Wishlists.UserId WHERE IsBilling ='true' AND (UserName LIKE '%'+#UserName+'%' OR (FirstName + LastName) LIKE '%'+#UserName+'%')";
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
{
SqlCommand cmd = new SqlCommand(sqlSelect2, cn);
cmd.Parameters.AddWithValue("#UserName", String.Format("%{0}%", SearchName.Text));
cmd.CommandType = CommandType.Text;
cn.Open();
DataSet ds = new DataSet();
DataTable jobsListsTbl2 = ds.Tables.Add("jobsListsTbl2");
jobsListsTbl2.Columns.Add("User", Type.GetType("System.String"));
jobsListsTbl2.Columns.Add("PrimaryAddress", Type.GetType("System.String"));
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
DataRow dr = jobsListsTbl2.NewRow();
dr["User"] = reader["UserName"];
dr["PrimaryAddress"] = reader["Address"];
jobsListsTbl2.Rows.Add(dr);
}
}
WishlistGrid.DataSource = ds;
WishlistGrid.DataMember = "jobsListsTbl2";
WishlistGrid.DataBind();
}
}//end if SearchLocation.Text is empty
}//end of if SearchName.Text !==''
}
catch (Exception x)
{
errors5.Text += "ERROR: " + x.Message.ToString() + "<br />";
}
}
protected void SearchButton_Click(object sender, EventArgs e)
{
WishlistGrid.Visible = true;
getJobLists();
}
And this is the designer code for the search form (Note: the NavigateUrl is not set for the hyperlink yet. I will set it once everything is displaying properly for the search results):
<div id="findWishlistPage" class="mainContentWrapper">
<div class="section">
<div class="introDiv">
<div class="pageHeader">
<h1>Find a Job List</h1>
</div>
<div class="content">
<asp:label id="errors" runat="server" text=""></asp:label>
<asp:label id="errors2" runat="server" text=""></asp:label>
<asp:label id="errors3" runat="server" text=""></asp:label>
<asp:label id="errors4" runat="server" text=""></asp:label>
<asp:label id="errors5" runat="server" text=""></asp:label>
<asp:UpdatePanel ID="Searchajax" runat="server">
<ContentTemplate>
<asp:Panel ID="SearchPanel" runat="server" EnableViewState="false" DefaultButton="SearchButton">
<asp:ValidationSummary ID="ValidationSummary1" runat="server" EnableViewState="false" />
<table class="inputForm">
<tr>
<th class="rowHeader">
<asp:Label ID="SearchNameLabel" runat="server" Text="Name or E-mail:" AssociatedControlID="SearchName" EnableViewState="false"></asp:Label>
</th>
<td>
<asp:Textbox id="SearchName" runat="server" onfocus="this.select()" Width="200px" EnableViewState="false"></asp:Textbox>
<asp:RequiredFieldValidator ID="SearchNameValdiator" runat="server" ControlToValidate="SearchName"
Text="*" ErrorMessage="Name or email address is required." EnableViewState="false"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<th class="rowHeader">
<asp:Label ID="SearchLocationLabel" runat="server" Text="City or State (optional):" EnableViewState="false"></asp:Label>
</th>
<td>
<asp:TextBox id="SearchLocation" runat="server" onfocus="this.select()" Width="140px" EnableViewState="false"></asp:TextBox>
<asp:LinkButton ID="SearchButton" runat="server" CssClass="button linkButton" Text="Search" OnClick="SearchButton_Click" EnableViewState="false" />
</td>
</tr>
</table><br />
<asp:GridView ID="WishlistGrid" runat="server" AllowPaging="True"
AutoGenerateColumns="False" ShowHeader="true"
SkinID="PagedList" Visible="false" EnableViewState="false">
<Columns>
<asp:TemplateField HeaderText="Name">
<HeaderStyle CssClass="wishlistName" />
<ItemStyle CssClass="wishlistName" />
<ItemTemplate>
<asp:HyperLink ID="WishlistLink" runat="server" >
<%#Eval("User")%>
</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location">
<HeaderStyle CssClass="wishlistLocation" />
<ItemStyle CssClass="wishlistLocation" />
<ItemTemplate>
<asp:Label ID="Location" runat="server" Text='<%#Eval("PrimaryAddress")%>'></asp:Label>
<%--'<%#GetLocation(Eval("User.PrimaryAddress"))%>'--%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<asp:Localize ID="EmptySearchResult" runat="server" Text="There were no job lists matching your search criteria."></asp:Localize>
</EmptyDataTemplate>
</asp:GridView>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
</div>
Can anyone please tell me what I'm missing or doing wrong?
Okay, I finally solved the issue. Apparently, it was a variable naming issue I kept overlooking. But now it all works okay! :)
I have a problem.
I have a registration and some RequiredFieldValidator controlls.
Problem:
If i leave the textbox empty, then i can see the errormessage. But it write the values in my database. i want that it stops, and not writing the values in my DB.
Thank you very much!
Kevin
Aspx
<tr>
<td id="LabelBenutzername" class="auto-style2">Benutzername</td>
<td>
<asp:TextBox ID="TextBoxRBenutzername" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
runat="server" ControlToValidate="TextBoxRBenutzername"
ErrorMessage="Bitte einen Benutzernamen eingeben" ForeColor="Red">
</asp:RequiredFieldValidator>
</td>
</tr>
Codebehind
if (IsPostBack)
{
SqlCommand cmd = new SqlCommand("select * from tabUser where Benutzername = #Benutzername", con);
SqlParameter param = new SqlParameter();
param.ParameterName = "#Benutzername";
param.Value = TextBoxRBenutzername.Text;
cmd.Parameters.Add(param);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
Label1.Text = "User Id already exists";
con.Close();
return;
}
con.Close();
}
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBFitnessBlogConnectionString"].ToString());
SqlCommand cmd = new SqlCommand();
cmd.Connection = con; //assigning connection to command
cmd.CommandType = CommandType.Text; //representing type of command
//cmd.CommandText = "INSERT INTO UserDetails (Fname,Lname,Email,Password,Gender,Dob,Mobile,Address) values
// (#Fname,#Lname,#Email,#Password,#Gender,#Dob,#Mobile,#Address)";
cmd.CommandText = "INSERT INTO tabUser values(#Benutzername,#Passwort,#Vorname,#Nachname,#Email)";
//adding parameters with value
cmd.Parameters.AddWithValue("#Benutzername", TextBoxRBenutzername.Text.ToString());
cmd.Parameters.AddWithValue("#Passwort", TextBoxRPasswort.Text.ToString());
cmd.Parameters.AddWithValue("#Vorname", TextBoxRVorname.Text.ToString());
cmd.Parameters.AddWithValue("#Nachname", TextBoxRNachname.Text.ToString());
cmd.Parameters.AddWithValue("#Email", TextBoxREmail.Text.ToString());
con.Open(); //opening connection
cmd.ExecuteNonQuery(); //executing query
con.Close(); //closing connection
Label1.Text = "Registration erfolgreich..";
}
catch (Exception ex)
{
Label1.Text = "Registration erfolgreich NICHT..";
}
}
In your code-behind, wrap the database logic in a check to see if the page is valid or not, like this:
if(Page.IsValid)
{
// Do database logic here
}
Quick answer: In your code-behind file, write into the event to check for validation prior to proceeding with the database update.
protected void btnUpdateSettings_Click(object sender, EventArgs e)
{
if (IsValid)
{
// Event Programming Code Goes Here
}
}
The idea would be that if any controls had triggered validation controls, then the form could post-back, but then there would be no code execution.
Before you make your call to the database to update your data, check
Page.IsValid == true
before you make your update.
This should be false if your validation failed.
I don't see your submit button. But I have used your code to show you how I do mine. It looks like you are missing the ValidationGroup in both controls.
<tr>
<td id="LabelBenutzername" class="auto-style2">Benutzername</td>
<td>
<asp:TextBox ID="TextBoxRBenutzername" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBoxRBenutzername" ValidationGroup="Insert" ErrorMessage="Bitte einen Benutzernamen eingeben" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" Font-Size="Smaller" Height="29px" OnClick="btnSubmit_Click" Width="59px" ValidationGroup="Insert" CausesValidation="true" />
</td>
</tr>
I hope this helps.
Note that you can also use a validation summary.
I am reading a membership tutorial from ASP.NET
I am currently at the step titled:
Customizing the CreateUserWizard’s Interface to Prompt for the New
User’s Home Town, Homepage, and Signature
What is supposed to happen is that I add a custom "step" to my CreateUserWizard, but when I run through this custom Step and hit "Continue", the values are NOT inserted into my Database, and if something is going wrong, then it should insert "NULL" into the database (as the tutorial tells, "if the user closes the registration during step 2, it will automatically insert NULL", but even that doesn't happen.
My database have 1 relation from UserProfiles_Id to Aspnet_Users_UserId:
FK_UserProfiles_aspnet_Users
I have gone through the steps in the tutorial serval times and I am still unable to find the problem.
Aspx.:
<asp:CreateUserWizard ID="NewUserWizard" runat="server" ContinueDestinationPageUrl="~/bruger/info.aspx">
<WizardSteps>
<asp:CreateUserWizardStep ID="CreateUserWizardStep" runat="server">
</asp:CreateUserWizardStep>
<asp:WizardStep ID="UserSettings" runat="server" StepType="Step" Title="Dine Informationer">
<p>Navn:<br />
<asp:TextBox ID="Name" runat="server" TextMode="SingleLine" />
</p>
<p>Adresse:<br />
<asp:TextBox ID="Adress" Columns="40" runat="server" TextMode="SingleLine" />
</p>
<p>Postnummer:<br />
<asp:TextBox ID="ZipCode" Columns="20" Rows="5" runat="server" TextMode="SingleLine" />
</p>
<p>By:<br />
<asp:TextBox ID="City" Columns="40" runat="server" TextMode="SingleLine" />
</p>
</asp:WizardStep>
<asp:CompleteWizardStep ID="CompleteWizardStep1" runat="server" >
</asp:CompleteWizardStep>
</WizardSteps>
</asp:CreateUserWizard>
Aspx.cs:
protected void NewUserWizard_ActiveStepChanged(object sender, EventArgs e)
{
// Have we JUST reached the Complete step?
if (NewUserWizard.ActiveStep.Title == "Complete")
{
WizardStep UserSettings = NewUserWizard.FindControl("UserSettings") as
WizardStep;
// Programmatically reference the TextBox controls
TextBox Name = UserSettings.FindControl("Name") as TextBox;
TextBox Adress = UserSettings.FindControl("Adress") as TextBox;
TextBox ZipCode = UserSettings.FindControl("ZipCode") as TextBox;
TextBox City = UserSettings.FindControl("City") as TextBox;
// Update the UserProfiles record for this user
// Get the UserId of the just-added user
MembershipUser newUser = Membership.GetUser(NewUserWizard.UserName);
Guid newUserId = (Guid)newUser.ProviderUserKey;
// Insert a new record into UserProfiles
string connectionString =
ConfigurationManager.ConnectionStrings["LLCateringConnectionString"].ConnectionString;
string updateSql = #"UPDATE UserProfiles SET Name = #Name, Adress = #Adress, ZipCode = #ZipCode, City = #City
WHERE UserId = #UserId";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(updateSql, myConnection);
myCommand.Parameters.AddWithValue("#Name", Name.Text.Trim());
myCommand.Parameters.AddWithValue("#Adress", Adress.Text.Trim());
myCommand.Parameters.AddWithValue("#ZipCode", ZipCode.Text.Trim());
myCommand.Parameters.AddWithValue("#City", City.Text.Trim());
myCommand.Parameters.AddWithValue("#UserId", newUserId);
myCommand.ExecuteNonQuery();
myConnection.Close();
}
}
}
Try to change the line
if (NewUserWizard.ActiveStep.Title == "Complete")
to
if (NewUserWizard.ActiveStep == this.CompleteWizardStep1)