asp.net form submition into oracle database - c#

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

Related

ASP.net loginView control does not updating after user login

I'm creating a web site in vs 2017. I have a web form for logging in, which is verified against the web app database, and everything seems to work. However, when I log in to my web page, the loginView doesn't change. I am expecting some kind of display that the user has successfully logged into the web page.
Here's my code:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
private string mycon = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
private bool ValidateUser(String username, String password)
{
bool status;
SqlConnection con = new SqlConnection(mycon);
String myquery = "select * from customer";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = myquery;
cmd.Connection = con;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
String uname;
String pass;
uname = ds.Tables[0].Rows[0]["userName"].ToString();
pass = ds.Tables[0].Rows[0]["password"].ToString();
con.Close();
if (uname == username && pass == password)
{
Session["username"] = uname;
status = true;
}
else
{
status = false;
}
return status;
}
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
if (e.Authenticated)
{
Response.Redirect("Home.aspx");
}
if (ValidateUser(Login1.UserName, Login1.Password))
{
Response.Redirect("Home.aspx");
}
else
{
e.Authenticated = false;
}
}
}
and here is my login.aspx
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<script src="jquery/jQuery.js"></script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1"
Runat="Server">
<asp:Login ID="Login1" runat="server" CreateUserText="Register"
CreateUserUrl="~/Registeration.aspx" DestinationPageUrl="~/home.aspx"
Width="1539px" OnAuthenticate="Login1_Authenticate" InstructionText="please
enter your Username and Password to Login">
<LayoutTemplate>
<table cellpadding="1" cellspacing="0" style="border-collapse:
collapse;">
<tr>
<td>
<table cellpadding="0" style="width:1637px;">
<tr>
<td align="center" colspan="2">Log In</td>
</tr>
<tr>
<td align="center" colspan="2">please enter your Username and Password to Login</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"></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">
<asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label>
</td>
<td>
<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">
<asp:CheckBox ID="RememberMe" runat="server"
Text="Remember me next time." />
</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 colspan="2">
<asp:Button ID="LoginButton" runat="server"
CommandName="Login" Text="Log In" ValidationGroup="Login1" Width="120px" />
</td>
</tr>
<tr>
<td colspan="2">
<asp:HyperLink ID="CreateUserLink"
runat="server" NavigateUrl="~/Registeration.aspx">Register</asp:HyperLink>
</td>
</tr>
</table>
</td>
</tr>
</table>
</LayoutTemplate>
</asp:Login>
</asp:Content>
here is my home.aspx which the user will go to after logging in :
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="home.aspx.cs" Inherits="_Default" %>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<table border="1" style="width:100%" height="310">
<tr>
<th colspan="7">
<h1 style="text-align:center;">Welcome to BEAUTIC</h1>
<p style="text-align:center;">where every girl can have a healthy and beautiful skin</p>
</th>
<th colspan="3">
<asp:image runat="server" Height="250px" ImageUrl="~/images/makeup.png" Width="300px"></asp:image>
</th>
</tr>
</table>
</asp:Content>
there is no code behind for this page.
And this is my LoginView Control (it is located in the master page):
<th colspan="1" class="auto-style1">
<asp:LoginView ID="LoginView1" runat="server">
<AnonymousTemplate>
Hello,<br />
<asp:LoginStatus ID="LoginStatus1" runat="server" CssClass="auto-style3" />
</AnonymousTemplate>
<LoggedInTemplate>
<span class="auto-style3">Welcome back,</span><br class="auto-style2" />
<asp:LoginName ID="LoginName1" runat="server" CssClass="auto-style3" />
<br />
<asp:LoginStatus ID="LoginStatus2" runat="server" CssClass="auto-style2" />
</LoggedInTemplate>
</asp:LoginView>
</th>
i finally figured it out . so my error was in my login.aspx code behind page in this statement :
if (e.Authenticated)
{
Response.Redirect("Home.aspx");
}
if (ValidateUser(Login1.UserName, Login1.Password))
{
Response.Redirect("Home.aspx");
}
else
{
e.Authenticated = false;
}
so i think that e.authenticated = true didn't reach the login view because i redirected my self to the other page so all you need to do is to :
if
if (ValidateUser(Login1.UserName, Login1.Password))
{
e.Authenticated = true;
}
else
{
e.Authenticated = false;
}
and make sure to set the login property DestinationPageUrl to what you want the user to go after login .

String.Empty not working on button click

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

Value of boolean cell in gridview to shown in a radio button

I have a Boolea(bit) value in database and i shown it in Grid View in the cell no. 2 like this
MyGrdView.SelectedRow.Cells[2] // for any row selected this cell have a boolean value 0 or 1
The GridView in a View 1 in Multiview control
I need in another View (view2), i can shown this value in check box, so if the boolean cell in gridview have 0, the check box checked and for 1 the check box unchecked
ASP Code:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:MultiView ID="LocationsMultiView" runat="server" ActiveViewIndex="0">
<asp:View ID="View1" runat="server">
<div>
<div class="EU_TableScroll" id="showData" style="display: block">
<table class="auto-style1">
<tr>
<td>
<asp:Button ID="Btn_ShowReminders" runat="server" Text="Show Reminders" OnClick="Btn_ShowReminders_Click" />
<asp:Button ID="Btn_EditReminder" runat="server" Text="Edit Reminder" Enabled="False" OnClick="Btn_EditReminder_Click" />
<asp:Button ID="Btn_RemoveReminder" runat="server" Enabled="False" OnClick="Btn_RemoveReminder_Click" Text="Delete Reminder" />
</td>
</tr>
<tr>
<td>
<asp:Label ID="Lbl_Error" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:GridView ID="Grd_Reminders" runat="server" CssClass="EU_DataTable" GridLines="Horizontal" OnSelectedIndexChanged="Grd_Reminders_SelectedIndexChanged">
<Columns>
<asp:ButtonField ButtonType="Button" CommandName="Select" HeaderText="Select" ShowHeader="True" Text=">>>" />
</Columns>
</asp:GridView>
</td>
</tr>
<tr>
<td>
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
<ProgressTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl="~/img/ajax-loader.gif" />
</ProgressTemplate>
</asp:UpdateProgress>
</td>
</tr>
</table>
</div>
</div>
</asp:View>
<asp:View ID="View2" runat="server">
<table class="auto-style1">
<tr>
<td colspan="3">
<asp:Label ID="Lbl_EditRemTitle" runat="server" Text="Edit Reminder"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Label ID="Lbl_Edit_Title" runat="server" Text="Title"></asp:Label>
</td>
<td>
<asp:TextBox ID="Txt_EditTitle" runat="server"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="RequiredFieldValidator" ValidationGroup="g1" ControlToValidate="Txt_EditTitle">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:Label ID="Lbl_Edit_Content" runat="server" Text="Content"></asp:Label>
</td>
<td>
<asp:TextBox ID="Txt_Edit_Content" runat="server"></asp:TextBox>
</td>
<td> </td>
</tr>
<tr>
<td class="auto-style2">
<asp:Label ID="Lbl_Edit_Desc" runat="server" Text="Description"></asp:Label>
</td>
<td class="auto-style2">
<asp:TextBox ID="Txt_Edit_Description" runat="server" TextMode="MultiLine"></asp:TextBox>
</td>
<td class="auto-style2"> </td>
</tr>
<tr>
<td>
<asp:Label ID="Lbl_Edit_TurnOn" runat="server" Text="Turn On"></asp:Label>
</td>
<td>
<asp:CheckBox ID="CheckBox1" runat="server" />
</td>
<td> </td>
</tr>
<tr>
<td>
<asp:Label ID="Lbl_Edit_Alw" runat="server" Text="Always"></asp:Label>
</td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>
<asp:Label ID="Lbl_Edit_Public" runat="server" Text="Public"></asp:Label>
</td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>
<asp:Label ID="Lbl_Edit_Radius" runat="server" Text="Radius"></asp:Label>
</td>
<td> </td>
<td> </td>
</tr>
<tr>
<td colspan="3">
<asp:Label ID="Lbl_Edit_Msg" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:UpdateProgress ID="UpdateProgress2" runat="server">
</asp:UpdateProgress>
</td>
</tr>
<tr>
<td colspan="3">
<asp:Button ID="Button1" runat="server" Text="Save" ValidationGroup="g1" />
<asp:Button ID="Btn_Cancel_Edit" runat="server" OnClick="Btn_Cancel_Edit_Click" Text="Cancel" />
</td>
</tr>
</table>
</asp:View>
</asp:MultiView>
</ContentTemplate>
CS Code:
public partial class webusercontrols_remindersctl : System.Web.UI.UserControl
{
Locations Lo = new Locations();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Utilities.ReadFromCookie("logincookie", "user", Request) != null)
{
UserInfo UI = new UserInfo();
string userNameOnWB = Request.Cookies["logincookie"]["user"];
}
}
// Btn_ShowReminders_Click(null, null);
}
protected void Grd_Reminders_SelectedIndexChanged(object sender, EventArgs e)
{
Btn_RemoveReminder.Enabled = true;
Grd_Reminders.SelectedRow.BackColor = Color.FromName("#E56E94");
Btn_RemoveReminder.Enabled = true;
Btn_EditReminder.Enabled = true;
}
protected void Btn_ShowReminders_Click(object sender, EventArgs e)
{
Locations loc = new Locations();
string UserName = Request.Cookies["logincookie"]["user"];
Grd_Reminders.DataSource = loc.GetRemindersForUser(UserName);
Grd_Reminders.DataBind();
Grd_Reminders.SelectedIndex = -1;
Btn_RemoveReminder.Enabled = false;
Btn_EditReminder.Enabled = false;
Lbl_Error.Text = String.Empty;
}
protected void Btn_RemoveReminder_Click(object sender, EventArgs e)
{
int ID = Int32.Parse((Grd_Reminders.SelectedRow.Cells[1].Text).ToString());
if (Lo.RemoveLocations(ID))
{
Lbl_Error.Text = "Reminder Removed!";
}
else
{
Lbl_Error.Text = "Error Removing Reminder!";
}
Btn_RemoveReminder.Enabled = false;
Grd_Reminders.DataBind();
}
protected void Btn_EditReminder_Click(object sender, EventArgs e)
{
LocationsMultiView.ActiveViewIndex = 1;
if (Grd_Reminders.SelectedRow.Cells[5] != null)
Txt_EditTitle.Text = Grd_Reminders.SelectedRow.Cells[5].Text;
if (Grd_Reminders.SelectedRow.Cells[6] != null)
Txt_Edit_Content.Text = Grd_Reminders.SelectedRow.Cells[6].Text;
if (Grd_Reminders.SelectedRow.Cells[7] != null)
Txt_Edit_Description.Text = Grd_Reminders.SelectedRow.Cells[7].Text;
if (Grd_Reminders.SelectedRow.Cells[8] != null)
CheckBox1.Checked = Convert.ToBoolean(Grd_Reminders.SelectedRow.Cells[8]);
}
protected void Btn_Cancel_Edit_Click(object sender, EventArgs e)
{
LocationsMultiView.ActiveViewIndex = 0;
}
}

Update query not firing properly. Update does not reflect

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)
{
....
}
}

DropDownList1 does not exist in the current context

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.

Categories

Resources