asp.net RequiredFieldValidator - c#

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.

Related

Insert data from form field to SQL

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.

How to automatically filter a DropDown List values based on selected textbox in asp.net

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>

How do I show an associated value with a dropdown list item (after choosing it from the list)?

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.

Modal pop up AJAX exits when refresh

Here is the situation, I have a AJAX modal pop up, inside my panel is two(2) connected drop down list. One is for Continent, and the other one is for Countries. An example of it is when the user choose Asia, the drop down for countries should have data inside. here is my code for modal pop up and Panel
<asp:ModalPopupExtender ID="Modalpopupextender1" runat="server" TargetControlID="ShowPopUpButton"
PopupControlID="pnlpopup" CancelControlID="CancelButton" BackgroundCssClass="modalBackground">
</asp:ModalPopupExtender>
<asp:Panel ID="pnlpopup" runat="server" BackColor="White" Height="269px" Width="400px"
OnLoad="pnlpopup_Load">
<tr>
<td align="right">
Continent:
</td>
<td>
<asp:DropDownList ID="ContinentDownList" runat="server"
onselectedindexchanged="ContinentDropDownList_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
</td>
</tr>
<tr>
<td align="right">
Country:
</td>
<td>
<asp:DropDownList ID="CountryDropDownList" runat="server">
</asp:DropDownList>
</td>
</tr>
</asp:Panel>
Now my Problem is, When my Modal Pop up loads, When I choose a Continent, the drop down for Countries doesnt load. When I Inserted AutoPostBack="true" to my ContinentDropDown, the Modal Pop Up refreshes, and exits. Ive spend a long time debugging and knowing how to fix this. Help!
here is my code-behind
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadContinent();
LoadCountry();
}
}
public void LoadContinent()
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
using (SqlCommand com = new SqlCommand("Reader.usp_LoadContinentDropDownList", con))
{
com.CommandType = CommandType.StoredProcedure;
con.Open();
try
{
SqlDataReader dr = com.ExecuteReader();
OwnerGroupDropDownList.DataSource = dr;
OwnerGroupDropDownList.DataTextField = "fld_Description";
OwnerGroupDropDownList.DataValueField = "fld_ContinentID";
ContinentDropDownList.DataBind();
}
catch (SqlException)
{
Response.Write("<script>alert('The database has encountered an error. Please try again')</script>"); }
catch (Exception)
{
Response.Write("<script>alert('The database has encountered an error. Please try again')</script>"); }
}
}
LoadContinentDropDownList.Items.Insert(0, new ListItem("<Select Person Group>", "0"));
}
public void LoadCountry()
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
using (SqlCommand com = new SqlCommand("Reader.usp_LoadCountryDropDownList", con))
{
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add(new SqlParameter("#fld_ContinentId", SqlDbType.Int));
com.Parameters["#fld_ContinentId"].Value = ContinentDropDownList.SelectedValue;
con.Open();
try
{
SqlDataReader dr = com.ExecuteReader();
OwnerDropDownList.DataSource = dr;
OwnerDropDownList.DataTextField = "fld_Description";
OwnerDropDownList.DataValueField = "fld_CountryID";
CountryDownList.DataBind();
}
catch (SqlException)
{
Response.Write("<script>alert('The database has encountered an error. Please try again')</script>"); }
catch (Exception)
{
Response.Write("<script>alert('The database has encountered an error. Please try again')</script>"); }
}
}
CountryDropDownList.Items.Insert(0, new ListItem("<Select Person>", "0"));
}
protected void ContinentDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
LoadContinent();
LoadCountry();
}
Have you tried putting the pnlPopup panel inside of an ASP.NET UpdatePanel control? Now when your dropdown list does a postback, it will be a partial postback since they are both within an UpdatePanel and it should maintain the visibility on the popup panel.
Check out Introduction to the UpdatePanel Control for more information about creating and using the UpdatePanel.
When you put controls outside of an UpdatePanel, the AutoPostback="true" caused a full postback which "reset" the popup panel to hidden, since that is the default state for the modal popup extender's target control.

ActiveStepChanged In CreateUserWizard

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)

Categories

Resources