My Code Behind File is UpdatePublication.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
namespace SBAIMS
{
public partial class UpdatePublisher : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["P_Id"] != null)
{
string s = Request.QueryString["P_Id"].ToString();
SqlConnection con = new SqlConnection(#"Data Source=AP\sqlexpress;Initial Catalog=SBAIMS;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select * from Publication_Master where P_Id='" + s + "' ", con);
SqlDataAdapter adptr = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adptr.Fill(ds, "Publication_Master");
if (ds.Tables["Publication_Master"].Rows.Count > 0)
{
upub.Text = ds.Tables["Publication_Master"].Rows[0]["Publication"].ToString();
upname.Text = ds.Tables["Publication_Master"].Rows[0]["Publisher"].ToString();
upc1.Text = ds.Tables["Publication_Master"].Rows[0]["P_Contact"].ToString();
upc2.Text = ds.Tables["Publication_Master"].Rows[0]["P_Contact2"].ToString();
upemail.Text = ds.Tables["Publication_Master"].Rows[0]["P_Email"].ToString();
upban.Text = ds.Tables["Publication_Master"].Rows[0]["P_BankAccount"].ToString();
}
con.Close();
}
}
protected void submitupdatepub_Click(object sender, EventArgs e)
{
string s = Request.QueryString["P_Id"].ToString();
SqlConnection con2 = new SqlConnection(#"Data Source=AP\sqlexpress;Initial Catalog=SBAIMS;Integrated Security=True");
con2.Open();
SqlCommand cmd2 = new SqlCommand("UPDATE Publication_Master SET Publication='" + upub.Text + "', Publisher='" + upname.Text + "', P_Contact='" + upc1.Text + "', P_Contact2='" + upc2.Text + "', P_Email='" + upemail.Text + "', P_BankAccount='" + upban.Text + "' WHERE P_Id='"+s+"'", con2);
cmd2.ExecuteNonQuery();
con2.Close();
Response.Redirect("~/UPublisher.aspx");
}
}
}
My ASPX file is UpdatePublication.aspx
<%# Page Title="Update Publication" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
CodeBehind="UpdatePublication.aspx.cs" Inherits="SBAIMS.UpdatePublisher" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<div id="updatepublisher">
<table width="100%" class="table table-borderless table-responsive">
<tr>
<td width="50%" style="vertical-align: top;">
<div class="panel panel-success" id="updatepub">
<div class="panel-heading">
<h4>
<b>Update Publication.</b></h4>
</div>
<div class="panel-body">
<h5>
Update data about Publication.</h5>
<br />
<div align="center">
<asp:Label ID="updatepubsubmit" runat="server" Font-Size="Medium" Text="Update Was Successful !!"
CssClass="alert alert-success alcntr" Visible="False"></asp:Label>
</div>
<br />
<br />
<table class="table table-borderless table-responsive fs15" align="center" style="width: 500px; background-color: transparent;">
<tr>
<td width="40%">
Publication Name
</td>
<td width="60%">
<asp:TextBox ID="upub" CssClass="form-control fs15" autocomplete="off" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator8" runat="server" ErrorMessage="* Field Required"
ControlToValidate="upub" Display="Dynamic" SetFocusOnError="True" Font-Size="Medium"
CssClass="rfvlabel" ValidationGroup="rfvup"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
Publisher (/Distributor) Name
</td>
<td>
<asp:TextBox ID="upname" CssClass="form-control fs15" autocomplete="off" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator9" runat="server" ErrorMessage="* Field Required"
ControlToValidate="upname" Display="Dynamic" SetFocusOnError="True" Font-Size="Medium"
CssClass="rfvlabel" ValidationGroup="rfvup"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator9" runat="server" ErrorMessage="* Enter characters or valid symbols" ControlToValidate="upname" Display="Dynamic" SetFocusOnError="True" Font-Size="Medium"
CssClass="rfvlabel" ValidationExpression="^[a-zA-Z''-'\s]{1,40}$" ValidationGroup="rfvup"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
Contact No. 1
</td>
<td>
<asp:TextBox ID="upc1" CssClass="form-control fs15" autocomplete="off" placeholder="optional" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator10" runat="server" ErrorMessage="* Numbers Only"
ControlToValidate="upc1" Display="Dynamic" SetFocusOnError="True" Font-Size="Medium"
CssClass="rfvlabel" ValidationExpression="^([0-9]*)$" ValidationGroup="rfvup"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
Contact No. 2
</td>
<td>
<asp:TextBox ID="upc2" CssClass="form-control fs15" autocomplete="off" placeholder="optional" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator11" runat="server" ErrorMessage="* Numbers Only"
ControlToValidate="upc2" Display="Dynamic" SetFocusOnError="True" Font-Size="Medium"
CssClass="rfvlabel" ValidationExpression="^([0-9]*)$" ValidationGroup="rfvup"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
Publisher Bank A/C No.
</td>
<td>
<asp:TextBox ID="upban" CssClass="form-control fs15" autocomplete="off" placeholder="optional" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator12" runat="server" ErrorMessage="* Numbers Only"
ControlToValidate="upban" Display="Dynamic" SetFocusOnError="True" Font-Size="Medium"
CssClass="rfvlabel" ValidationExpression="^([0-9]*)$" ValidationGroup="rfvup"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
Pub. Email ID
</td>
<td>
<asp:TextBox ID="upemail" CssClass="form-control fs15" autocomplete="off" placeholder="optional" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator13" runat="server" ErrorMessage="* Please Enter Valid Email ID"
Display="Dynamic" CssClass="rfvlabel" ControlToValidate="upemail" ValidationGroup="rfvup"
ValidationExpression="^([0-9a-zZ-Z]([-.\w]*[0-9a-zA-Z])*#([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$"></asp:RegularExpressionValidator>
</td>
</tr>
</table>
<br />
<table class="table table-borderless table-responsive" align="center" style="width: 300px;
background-color: transparent;">
<tr>
<td colspan="2" align="center">
<asp:Button ID="submitupdatepublisher" runat="server" OnClick="submitupdatepub_Click" class="btn btn-success btn-block"
Font-Size="Large" Text="Update" ValidationGroup="rfvup" />
</td>
</tr>
</table>
</div>
</div>
</td>
<td></td>
</tr>
</table>
</div>
</asp:Content>
The update doesn't work successfully. I mean it does not reflect in database. It just according to code, redirects to the specified page. Please help me where i am going wrong.
Actually the problem is now solved. I thank all of you for your concerns.
The problem was solved by just putting if not postback condition.
if (!Page.IsPostBack)
{
if (Request.QueryString["P_Id"] != null)
{
....
}
}
Related
I am trying to get validation where i can check what user inter in TextBox is valid PartNumber which is in my database.
My asp page looks like . and code behind is
<table width="50%" border="1" align="center">
<tr>
<td width="30%" class="style1">
<b>Part Number :</b>
</td>
<td class="style1">
<asp:TextBox ID="lpartno" runat="server" Width="300px"></asp:TextBox>
<cc1:AutoCompleteExtender ServiceMethod="GetCompletionListPartno" MinimumPrefixLength="1"
CompletionInterval="1" EnableCaching="false" TargetControlID="lpartno"
ID="AutoCompleteExtender2" runat="server" FirstRowSelected="false">
</cc1:AutoCompleteExtender>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="lpartno" TargetControlID="lpartno" ErrorMessage="PartNumber is Required" ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td width="30%">
<b>Reveived Date :</b>
</td>
<td>
<asp:TextBox ID="lReceivedDate" runat="server" CausesValidation="True" ></asp:TextBox>
<cc1:CalendarExtender ID="lReceivedDate_CalendarExtender" runat="server" Enabled="True"
TargetControlID="lReceivedDate">
</cc1:CalendarExtender>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="lReceivedDate" TargetControlID="lReceivedDate" ErrorMessage="Reveived Date is Required" ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td width="30%">
<b>PO Number :</b>
</td>
<td>
<asp:TextBox ID="lPONo" runat="server" Width="300px"></asp:TextBox>
<cc1:AutoCompleteExtender ServiceMethod="GetCompletionListPONo" MinimumPrefixLength="1"
CompletionInterval="1" EnableCaching="false" TargetControlID="lPONo"
ID="AutoCompleteExtender3" runat="server" FirstRowSelected="false">
</cc1:AutoCompleteExtender>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="lPONo" TargetControlID="lPONo" ErrorMessage="PO Number is Required" ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
I would like to have validation we i can check the Part number user is entering is in my database table. if not it should so some error message.
Please advice how i will achieve this !!
Thanks in advance !!
This is the way I solved this problem
protected void CustomValidator2_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = false;
string StaffID = lpartno.Text;
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["eFoxNetConnectionString"].ConnectionString;
SqlDataAdapter da = new SqlDataAdapter("select distinct PartNo from dbo.FTX_SAPPO sp with (nolock) where PartNo=#ID",conn);
da.SelectCommand.Parameters.Add("#ID", SqlDbType.VarChar, 120);
da.SelectCommand.Parameters["#ID"].Value = StaffID;
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
args.IsValid = true;
}
I'm working with ASP.NET web application . i have done a registration form but whenever the user type the Username or Email it will loads whole first_home page ! how i can stop loading the whole page ? i have setup a constraint in the database for the Username and Email to avoid the duplication.
the HTML code:
<table align="left" class="auto-style8" dir="rtl">
<tr>
<td class="auto-style13">username </td>
<td class="auto-style10">
<br />
<asp:TextBox ID="TextBoxUsername" runat="server" AutoPostBack="true" Height="25px" Width="223px" ForeColor="#990033" OnTextChanged="TextBoxUsername_TextChanged"></asp:TextBox>
<br />
</td>
<td class="auto-style11">
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="TextBoxUsername" ErrorMessage="write username"></asp:RequiredFieldValidator>
</td>
<td>
</td>
</tr>
<tr>
<td class="auto-style13">password</td>
<td class="auto-style10">
<br />
<asp:TextBox ID="TextBoxPassword" runat="server" Height="25px" Width="223px" ForeColor="#990033" TextMode="Password" OnTextChanged="TextBoxPassword_TextChanged"></asp:TextBox>
<br />
</td>
<td class="auto-style11">
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="TextBoxPassword" ErrorMessage="must write the password"></asp:RequiredFieldValidator>
</td>
<td>
</td>
</tr>
<tr>
<td class="auto-style13">confirm password </td>
<td class="auto-style10">
<br />
<asp:TextBox ID="TextBoxCPassword" runat="server" Height="25px" Width="223px" ForeColor="#990033" TextMode="Password" OnTextChanged="TextBoxCPassword_TextChanged"></asp:TextBox>
<br />
</td>
<td class="auto-style11">
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="TextBoxCPassword" ErrorMessage="must write the password"></asp:RequiredFieldValidator>
<br />
<asp:CompareValidator ID="CompareValidator1" runat="server" ControlToCompare="TextBoxPassword" ControlToValidate="TextBoxCPassword" ErrorMessage="wrong password"></asp:CompareValidator>
</td>
<td>
</td>
</tr>
<tr>
<td class="auto-style13">email</td>
<td class="auto-style10">
<br />
<asp:TextBox ID="TextBoxEmail" runat="server" AutoPostBack="true" Height="25px" Width="223px" ForeColor="#990033" TextMode="Email" OnTextChanged="TextBoxEmail_TextChanged"></asp:TextBox>
<br />
</td>
<td class="auto-style11">
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="TextBoxEmail" ErrorMessage="must write email"></asp:RequiredFieldValidator>
<br />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="TextBoxEmail" ErrorMessage="the email no valid" ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
</td>
<td>
</td>
</tr>
<tr>
<td class="auto-style13"> </td>
<td class="auto-style10">
<asp:Button ID="Button6" runat="server" OnClick="Button6_Click" Text="done" ForeColor="#990033" />
</td>
<td class="auto-style11"> </td>
<td> </td>
</tr>
</table>
the first_home.aspx.cs code:
public partial class First_home : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString);
conn.Open();
// check if the username is taken before
string checkuser = "Select count(*) from Users where Username='" + TextBoxUsername.Text + "'";
SqlCommand com = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
if (temp == 1)
{ Response.Write("error"); }
conn.Close();
}
}
protected void Button6_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString);
conn.Open();
string insertQuery = "insert into Users (Username,Password,Email) values (#username, #password, #email)";
SqlCommand com = new SqlCommand(insertQuery, conn);
com.Parameters.AddWithValue("#username", TextBoxUsername.Text);
com.Parameters.AddWithValue("#password", TextBoxPassword.Text);
com.Parameters.AddWithValue("#email", TextBoxEmail.Text);
com.ExecuteNonQuery();
conn.Close();
Response.Redirect("Seller_Registration.aspx");
}
catch (Exception ex)
{ Response.Write("error "); }
}
also the database CONSTRAINT :
CONSTRAINT [AK_Users_Email] UNIQUE NONCLUSTERED ([Email] ASC),
CONSTRAINT [AK_Users_Username] UNIQUE NONCLUSTERED ([Username] ASC),
Remove the AutoPostBack="true" attribute from those two controls.
Those two controls are causing PostBack whenever you are typing something and focusing out of that control. That is the reason behind the whole page load.
I am trying to clear the form on cancel button click with a function clearForm() that uses String.Empty with each field of the form but this is not working. I am neither getting any error nor getting the expected result.
Here's my design code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="AddEmployee.aspx.cs" Inherits="AddEmployee" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Add Employee</title>
<link href="css/Style.css" type="text/css" rel="Stylesheet" />
</head>
<body>
<form id="form1" runat="server">
<ajax:ToolkitScriptManager ID="toolkit1" runat="server"></ajax:ToolkitScriptManager>
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<table align="center" class="loginBox">
<tr>
<th colspan="2" style="color:White; font-size:medium; padding-bottom:10px;" align="left">Personal Information</th>
</tr>
<tr>
<td>Name:</td>
<td><asp:TextBox ID="txtName" CssClass="signup_textbox" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqName" ControlToValidate="txtName" runat="server" Display="None" ErrorMessage="Name" ></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>Address</td>
<td><asp:TextBox TextMode="MultiLine" Height="40" Width="135" ID="txtAddress" CssClass="signup_textbox" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqAdd" ControlToValidate="txtAddress" runat="server" Display="None" ErrorMessage="Address" ></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>DoB:</td>
<td>
<asp:TextBox ID="txtDoB" CssClass="signup_textbox cal_box" runat="server" />
<ajax:CalendarExtender ID="CalendarExtender1" TargetControlID="txtDoB" Format="dd/MM/yyyy" runat="server"></ajax:CalendarExtender>
</td>
</tr>
<tr>
<td>Gender</td>
<td>
<asp:RadioButtonList CssClass="signup_textbox" ID="GenderList" runat="server" RepeatDirection="Horizontal">
<asp:ListItem Selected="True">Male</asp:ListItem>
<asp:ListItem>Female</asp:ListItem>
</asp:RadioButtonList>
</td>
</tr>
<tr>
<th colspan="2" style="color:White; font-size:medium; padding-bottom:10px;" align="left">Professional Information</th>
</tr>
<tr>
<td>Department:</td>
<td>
<asp:DropDownList ID="ddlDept" CssClass="signup_textbox" runat="server"></asp:DropDownList>
</td>
</tr>
<tr>
<td>Designation:</td>
<td><asp:TextBox ID="txtDesig" CssClass="signup_textbox" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqDesig" ControlToValidate="txtDesig" runat="server" Display="None" ErrorMessage="Designation" ></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>Salary:</td>
<td><asp:TextBox ID="txtSal" CssClass="signup_textbox" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqSal" ControlToValidate="txtSal" runat="server" Display="None" ErrorMessage="Salary" ></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator runat="server" id="rexSal" controltovalidate="txtSal" validationexpression="^[0-9]{5}$" errormessage="Salary must be max 5 digits" Display="None" />
</td>
</tr>
<tr>
<th colspan="2" style="color:White; font-size:medium; padding-bottom:10px;" align="left">Login Information</th>
</tr>
<tr>
<td>Email:</td>
<td>
<asp:TextBox ID="txtEmail" CssClass="signup_textbox" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqEmail" ControlToValidate="txtEmail" runat="server" Display="None" ErrorMessage="Email" ></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="valEmail" runat="server" ErrorMessage="Invalid Email" ControlToValidate="txtEmail" ValidationExpression="^([\w\.\-]+)#([\w\-]+)((\.(\w){2,3})+)$" CssClass="error_msg" Display="none" />
</td>
</tr>
<tr>
<td>Username:</td>
<td>
<asp:TextBox ID="txtUser" CssClass="signup_textbox" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqUser" ControlToValidate="txtUser" runat="server" Display="None" EnableClientScript="true" SetFocusOnError="true" ErrorMessage="Username" ></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" Display="None" ControlToValidate="txtUser" ValidationExpression="^[\s\S]{3,}$" runat="server" ErrorMessage="Username must have at least 3 characters required."></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>Password:</td>
<td><asp:TextBox ID="txtPass" CssClass="signup_textbox" runat="server" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqPass" ControlToValidate="txtPass" runat="server" Display="None" EnableClientScript="true" SetFocusOnError="true" ErrorMessage="Password" ></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>Confirm Password:</td>
<td><asp:TextBox ID="txtConfPass" CssClass="signup_textbox" runat="server" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqConfPass" ControlToValidate="txtConfPass" runat="server" Display="None" EnableClientScript="true" SetFocusOnError="true" ErrorMessage="Confirm Password" ></asp:RequiredFieldValidator>
<asp:CompareValidator ID="cmpPass" runat="server" ControlToCompare="txtPass" ControlToValidate="txtConfPass" ErrorMessage="Password must match" CssClass="error_msg" Display="None"></asp:CompareValidator>
</td>
</tr>
<tr>
<td align="center" colspan="2" style="padding:5px;"><span><asp:Button ID="btnRegister" Width="60" runat="server" Text="Register" CssClass="btnLogin" OnClick="btn_AddEmp" /></span>
<span><asp:Button ID="btnClr" Width="60" runat="server" Text="Cancel" CssClass="btnLogin" OnClick="btn_ClearForm" /></span>
</td>
</tr>
</table>
<asp:Panel ID="errorsPanel" runat="server" Style="display: none; border-style: solid; border-width: thin; border-color: #FFDBCA" Width="175px" BackColor="White">
<asp:ValidationSummary ID="valSummary" runat="server" CssClass="error_msg" HeaderText="You must enter following" DisplayMode="BulletList" EnableClientScript="true" ShowSummary="true" />
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
Here's my code-behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
public partial class AddEmployee : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn_ClearForm(object sender, EventArgs e) //to clear form on IsPostBack or on press of cancel button
{
if (!IsPostBack)
{
clearForm();
}
}
#region public functions
public void clearForm()
{
txtName.Text = String.Empty;
txtAddress.Text = String.Empty;
txtDoB.Text = String.Empty;
txtDesig.Text = String.Empty;
txtSal.Text = String.Empty;
txtEmail.Text = String.Empty;
txtUser.Text = String.Empty;
txtPass.Text = String.Empty;
txtConfPass.Text = String.Empty;
GenderList.Items[0].Selected = true;
GenderList.Items[1].Selected = false;
}
#endregion
}
There is nothing wrong with string.Empty. But you do not need condition in btn_ClearForm as btn_ClearForm handler will always called on postback and you put the condition if !IsPostBack
// if (!IsPostBack)
//{
clearForm();
// }
Your code would be
protected void btn_ClearForm(object sender, EventArgs e)
{
clearForm();
}
Got the fix!
Just use CausesValidation="false" on the cancel button so as to disable validation upon cancel button click event.
Because when you have used validation on your controls without using CausesValidation="false" on the cancel button, your controls will be forced to pass through validation conditions given to them and since the cancel button is meant to clear your form regardless of checking the validity of the data in form fields, the form will get stuck.
So whenever you have used validation conditions on your controls, just make sure you don't get them fired on the click of Cancel/clear/reset button.
Thanks
I am beginer in asp.net. I have created a form. When i submit that form i need to insert the form field values into a table in oracle database schema. I am using Visual Studio 2012 Express. I have already added my database schema to database explorer. Now I need a code to get data from form and insert into table.
Default.aspx code:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="Demo._Default" %>
<asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">
</asp:Content>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<table align="center" class="auto-style1">
<tr>
<td class="auto-style2">Activity Type</td>
<td>
<asp:DropDownList ID="ActivityTypeDropDown" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ActivityTypeDropDown_SelectedIndexChanged" >
<asp:ListItem Text="--Select" Value="" />
<asp:ListItem>Ticket</asp:ListItem>
<asp:ListItem>Non-Ticket</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="ActivityTypeDropDown" ErrorMessage="Please select Activity Type">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="auto-style2">
<asp:Label ID="TktnoLable" runat="server" Text="Ticket NO"></asp:Label>
</td>
<td>
<asp:TextBox ID="TicketNoTextBox" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator8" runat="server" ControlToValidate="TicketNoTextBox" ErrorMessage="Please enter the ticket number">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="auto-style2">Ticket Category</td>
<td>
<asp:DropDownList ID="TicketCategoryTextBox" runat="server">
<asp:ListItem>--Select--</asp:ListItem>
<asp:ListItem>Adhoc</asp:ListItem>
<asp:ListItem>Batch Run</asp:ListItem>
<asp:ListItem>Bug Fix</asp:ListItem>
<asp:ListItem>CR</asp:ListItem>
<asp:ListItem>Enhancement</asp:ListItem>
<asp:ListItem>Issue</asp:ListItem>
<asp:ListItem>Others</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td class="auto-style2">Ticket Description</td>
<td>
<asp:TextBox ID="TicketDescriptionTextBox" TextMode="MultiLine" runat="server" Width="200px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator9" runat="server" ControlToValidate="TicketDescriptionTextBox" ErrorMessage="Please provide ticket description">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="auto-style7">Activity Description</td>
<td class="auto-style8">
<asp:TextBox ID="activityDescriptionTextBox" TextMode="MultiLine" runat="server" Width="200px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator10" runat="server" ControlToValidate="activityDescriptionTextBox" ErrorMessage="Please provide activity description">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="auto-style2">Module</td>
<td>
<asp:TextBox ID="ModuleTextBox" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style3">Priority</td>
<td class="auto-style4">
<asp:DropDownList ID="PriorityDropDown" runat="server">
<asp:ListItem Text="--Select--" Value="" />
<asp:ListItem>High</asp:ListItem>
<asp:ListItem>Medium</asp:ListItem>
<asp:ListItem>Low</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="PriorityDropDown" ErrorMessage="Please select priority">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="auto-style2">Resource</td>
<td>
<asp:DropDownList ID="ResourceDropDown" runat="server">
<asp:ListItem text="--Select--" Value="" />
<asp:ListItem>Apporva</asp:ListItem>
<asp:ListItem>Arun</asp:ListItem>
<asp:ListItem>Harshal</asp:ListItem>
<asp:ListItem>Kiran</asp:ListItem>
<asp:ListItem>Nitin</asp:ListItem>
<asp:ListItem>Vagmita</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="ResourceDropDown" ErrorMessage="Please Select a resource">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="auto-style2">Creation Date</td>
<td>
<asp:TextBox ID="CreationDateTextBox" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ControlToValidate="CreationDateTextBox" ErrorMessage="Please provide creation date">*</asp:RequiredFieldValidator>
<asp:CompareValidator ID="creationdatevalidator" runat="server" ControlToValidate="CreationDateTextBox" ErrorMessage="Please enter valid creation date" Operator="DataTypeCheck" Type="Date">*</asp:CompareValidator>
</td>
</tr>
<tr>
<td class="auto-style2">Assignment Date</td>
<td>
<asp:TextBox ID="AssignmentDateTextBox" runat="server"></asp:TextBox>
<asp:CompareValidator ID="assignmentdatevalidator" runat="server" ControlToValidate="AssignmentDateTextBox" ErrorMessage="please enter valid assignment date" Operator="DataTypeCheck" Type="Date">*</asp:CompareValidator>
</td>
</tr>
<tr>
<td class="auto-style3">Status</td>
<td class="auto-style4">
<asp:DropDownList ID="StatusDropDown" runat="server" AutoPostBack="True" OnSelectedIndexChanged="StatusDropDown_SelectedIndexChanged">
<asp:ListItem Text="--select--" Value="" />
<asp:ListItem>WIP</asp:ListItem>
<asp:ListItem>Completed</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server" ControlToValidate="StatusDropDown" ErrorMessage="Please select status">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="auto-style2">
<asp:Label ID="CompletionDateLable" runat="server" Text="Completion Date"></asp:Label>
</td>
<td>
<asp:TextBox ID="CompletionDateTextBox" runat="server"></asp:TextBox>
<asp:CompareValidator ID="completiondatevalidator" runat="server" ErrorMessage="Please enter valid completion date" Operator="DataTypeCheck" Type="Date" ControlToValidate="CompletionDateTextBox">*</asp:CompareValidator>
</td>
</tr>
<tr>
<td class="auto-style5">Remarks</td>
<td class="auto-style6">
<asp:TextBox ID="RemarksTextBox" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style2">Efforts</td>
<td>
<asp:TextBox ID="EffortsTextBox" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style2"> </td>
<td>
<asp:ValidationSummary ID="ValidationSummary1" runat="server" />
<br />
<br />
<input id="SubmitButton" type="submit" value="Submit" /><asp:Button ID="ResetButton" runat="server" OnClick="ResetButton_Click" Text="Reset" />
<asp:Label ID="Label1" runat="server"></asp:Label>
</td>
</tr>
</table>
</asp:Content>
<asp:Content ID="Content1" runat="server" contentplaceholderid="HeadContent">
<style type="text/css">
.auto-style1 {
width: 100%;
}
.auto-style2 {
width: 119px;
}
.auto-style3 {
width: 119px;
height: 31px;
}
.auto-style4 {
height: 31px;
}
.auto-style5 {
width: 119px;
height: 28px;
}
.auto-style6 {
height: 28px;
}
.auto-style7 {
width: 119px;
height: 47px;
}
.auto-style8 {
height: 47px;
}
</style>
</asp:Content>
Default.aspx.cs code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Oracle.DataAccess;
using Oracle.DataAccess.Client;
namespace Demo
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
var Activity_type = "";
var Ticket_no = "";
var tkt_category = "";
var tkt_desc = "";
var Act_desc = "";
var module = "";
var priority = "";
var resource = "";
var creation_date = "";
var Assigned_date = "";
var status = "";
var completed_date = "";
var remarks = "";
var Efforts = "";
if (IsPostBack)
{
Activity_type = Request.Form["ActivityTypeDropDown"];
Ticket_no = Request.Form["TicketNoTextBox"];
tkt_category = Request.Form["TicketCategoryTextBox"];
tkt_desc = Request.Form["TicketDescriptionTextBox"];
Act_desc = Request.Form["activityDescriptionTextBox"];
module = Request.Form["ModuleTextBox"];
priority = Request.Form["PriorityDropDown"];
resource = Request.Form["ResourceDropDown"];
resource = Request.Form["ResourceDropDown"];
creation_date = Request.Form["CreationDateTextBox"];
Assigned_date = Request.Form["AssignmentDateTextBox"];
status = Request.Form["StatusDropDown"];
completed_date = Request.Form["CompletionDateTextBox"];
remarks = Request.Form["RemarksTextBox"];
Efforts = Request.Form["EffortsTextBox"];
}
}
protected void ActivityTypeDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
if (ActivityTypeDropDown.SelectedValue == "Ticket")
{
TktnoLable.Visible = true;
TicketNoTextBox.Visible = true;
}
else
{
TktnoLable.Visible = false;
TicketNoTextBox.Visible = false;
}
}
protected void ResetButton_Click(object sender, EventArgs e)
{
ClearInputs(Page.Controls);
}
void ClearInputs(ControlCollection ctrls)
{
foreach (Control ctrl in ctrls)
{
if (ctrl is TextBox)
((TextBox)ctrl).Text = string.Empty;
ClearInputs(ctrl.Controls);
}
}
protected void StatusDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
if (StatusDropDown.SelectedValue == "Completed")
{
CompletionDateLable.Visible = true;
CompletionDateTextBox.Visible = true;
}
else
{
CompletionDateLable.Visible = false;
CompletionDateTextBox.Visible = false;
}
}
}
}
Please help me to complete the form action.
Here is simple method to insert data, you can modify it to your needs
public void InsertToOracle(string value)
{
string oradb = "Data Source=ORCL;User Id=user;Password=password;";
using (OracleConnection conn = new OracleConnection(oradb))
{
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "Insert into Table1(ColumnName) VALUES(#ParameterName)";
cmd.Parameters.Add(new OracleParameter("#ParameterName", value));
var rowsUpdated = cmd.ExecuteNonQuery();
}
}
In addition in asp.net web forms no needs to use Request.Form
instead of
tkt_category = Request.Form["TicketCategoryTextBox"];
use
tkt_category = TicketCategoryTextBox.Text;
instead of
Activity_type = Request.Form["ActivityTypeDropDown"];
use
Activity_type = ActivityTypeDropDown.SelectedValue;
All items marked with runat=server are ready to use as a object variable
I have added DropDownList1 in Default.aspx page my ASP.Net project, and I have the below code in Default.cs:
if(DropDownList1.SelectedItem.ToString()=="")
I got this error:
Error 2 The name 'DropDownList1' does not exist in the current context
Edit:
In *.cs:
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
string username = Login1.UserName;
string pwd = Login1.Password;
var connstring = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString; ;
var conn = new SqlConnection(connstring);
conn.Open();
SqlCommand command;
if(DropDownList1.SelectedItem.ToString()=="")
command = new SqlCommand("Select [ID] from [Inspector] WHERE [ID] =" + username + " AND [Password] ='" + pwd + "';", conn);
SqlDataReader dr = command.ExecuteReader();
if (dr.Read())
{
if (dr[0].ToString() == username)
{
Session["UserAuthentication"] = username;
Session.Timeout = 1;
Response.Redirect("MainInspector.aspx");
}
else
{
Session["UserAuthentication"] = "";
}
}
}
In *.aspx:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent" >
<style type="text/css">
.style1
{
height: 26px;
}
</style>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent" >
<h2>
الصفحة الرئيسية</h2>
<p>
الرجاء تسجيل الدخول:</p>
<p>
<asp:Login ID="Login1" runat="server"
FailureText="لم يتم تسجيل دخولك، الرجاء المحاولة ثانية."
LoginButtonText="تسجيل الدخول" onauthenticate="Login1_Authenticate"
PasswordLabelText="كلمة المرور:" RememberMeText="تذكرني في المرات القادمة"
TitleText="نسترعي إنتباهك أن كلمة المرور حساسة لحالة الأحرف"
UserNameLabelText="رقم الهوية:">
<LayoutTemplate>
<table cellpadding="1" cellspacing="0" style="border-collapse:collapse;">
<tr>
<td>
<table cellpadding="0">
<tr>
<td align="center" colspan="2">
نسترعي إنتباهك أن كلمة المرور حساسة لحالة الأحرف</td>
</tr>
<tr dir="rtl">
<td align="right">
<asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">رقم الهوية:</asp:Label>
</td>
<td>
<asp:TextBox ID="UserName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="UserNameRequired" runat="server"
ControlToValidate="UserName" ErrorMessage="User Name is required."
ToolTip="User Name is required." ValidationGroup="Login1">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="right" class="style1">
<asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">كلمة المرور:</asp:Label>
</td>
<td class="style1">
<asp:TextBox ID="Password" runat="server" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="PasswordRequired" runat="server"
ControlToValidate="Password" ErrorMessage="Password is required."
ToolTip="Password is required." ValidationGroup="Login1">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td colspan="2">
تسجيل الدخول بوصفك:<br />
<asp:CheckBox ID="RememberMe" runat="server" Text="تذكرني في المرات القادمة" />
<br />
</td>
</tr>
<tr>
<td align="center" colspan="2" style="color:Red;">
<asp:Literal ID="FailureText" runat="server" EnableViewState="False"></asp:Literal>
<br />
</td>
</tr>
<tr>
<td align="right" colspan="2">
<asp:Button ID="LoginButton" runat="server" CommandName="Login"
Text="تسجيل الدخول" ValidationGroup="Login1" />
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>فاحص</asp:ListItem>
<asp:ListItem>مُدرب</asp:ListItem>
<asp:ListItem>مُتدرب</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
</table>
</td>
</tr>
</table>
</LayoutTemplate>
</asp:Login>
</p>
</asp:Content>
You need to check your markup to confirm that the ID matches i.e.
<asp:DropDownList id="DropDownList1".....
If it is a web application the designer.cs file could be messed up as this has the reference within it.
Something like this:
protected global::System.Web.UI.WebControls.DropDownList DropDownList1;
If it is missing try adding the above.
Such errors might appear when the markup in the .aspx page (or .ascx control) is not well formed. In cases where the markup is bad, when you add a new control its declaration is not added in the designer file and leads to this error.
If this is the case, one common trick to fix this is to cut and paste the markup of the control. This way you re-add the control and make Visual Studio to re-add the declaration of the control in the designer file.
DropDownList1 does not exist in the current context
The solution for me was to place the DropDownList outside of of the LoginView.
Try moving the DropDownList to another section of your page and see if this works.