DropDownList1 does not exist in the current context - c#

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.

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 .

Unable to hide and show text boxes after refresh the page

I am trying to hide and show text boxes by radio button using jquery. I can show and hide text boxes but the error is I have a drop-down list. When I select drop-down value the page getting refreshed. After page refresh I am unable to do hiding and showing of text boxes. I have update panel for ajax. Why I am unable to hide and show text boxes after page refresh? Here is my source code. Please help me.
<%# Page Title="" Language="C#" MasterPageFile="~/Home.Master" AutoEventWireup="true" CodeBehind="ExperienceADD.aspx.cs" Inherits="Manjilas.WebForm31"%>
<%# Register Namespace="AjaxControlToolkit" Assembly="AjaxControlToolkit" tagPrefix="ajax" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" runat="server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<head>
<script src="Scripts2/jquery-1.7-vsdoc.js"></script>
<script src="Scripts2/jquery-1.7.js"></script>
<script src="Scripts2/jquery-1.7.min.js"></script>
<script type="text/javascript">
$(function () {
$('input[name="type"]').on('click', function () {
if ($(this).val() == 'Experienced') {
$('#txtcomp').Show();
$('#txtfrom').Show();
$('#txtto').Show();
} else {
$('#txtcomp').hide();
$('#txtcomp').hide();
$('#txtfrom').hide();
$('#txtto').hide();
}
});
});
</script>
</head>
<div class="container-fluid">
<div class="row-fluid">
<div class="well span5 center login-box">
<div class="alert alert-info">
<b><font size="4">ADD EXPERIENCE DETAILS</font></b>
</div>
<form id="form1" runat="server">
<asp:UpdatePanel ID="updatepanel1" runat="server"><ContentTemplate>
<div>
<ajaxToolkit:ToolkitScriptManager runat="server">
</ajaxToolkit:ToolkitScriptManager>
<asp:UpdatePanel ID="updatepanel2" runat="server"></asp:UpdatePanel>
<fieldset>
<table class="ui-accordion">
<tr>
<td align="left" class="style2">
MachID</td>
<td align="left">
<%-- <div class="input-prepend" title="Select Country Name">--%>
<asp:DropDownList ID="ddid" runat="server" AutoPostBack="True"
onselectedindexchanged="ddid_SelectedIndexChanged">
</asp:DropDownList>
</td>
</tr>
<tr>
<td align="left" class="style2">
<asp:Label ID="Empcode" runat="server" Text="EmpCode"></asp:Label>
<td align="left">
<asp:TextBox ID="txtname" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td align="left" class="style2">
</td>
<td align="left">
<input type="radio" name="type" value="Fresher" />Fresher
<input type="radio" name="type" value="Experienced" />Experienced
</td>
</tr>
<tr>
<td align="left" class="style2">
Company</td>
<td align="left">
<div class="input-prepend" title="Autogenerated District ID" data-rel="tooltip">
<asp:TextBox ID="txtcomp" runat="server" TextMode="SingleLine"></asp:TextBox>
</td>
</tr>
<tr>
<td align="left" class="style2">
From Date</td>
<td align="left">
<div class="input-prepend" title="Enter District Name" data-rel="tooltip">
<asp:TextBox ID="txtfrom" runat="server" TextMode="SingleLine"></asp:TextBox>
<ajax:CalendarExtender ID="Calendarextender1" TargetControlID ="txtfrom" Format="dd/MM/yyyy" runat="server"></ajax:CalendarExtender>
</td>
</tr>
<tr>
<td align="left" class="style2">
To Date</td>
<td align="left">
<div class="input-prepend" title="Enter District Name" data-rel="tooltip">
<asp:TextBox ID="txtto" runat="server" TextMode="SingleLine"></asp:TextBox>
<ajax:CalendarExtender ID="Calendarextender2" TargetControlID ="txtto" Format="dd/MM/yyyy" runat="server"></ajax:CalendarExtender>
</td>
</tr>
<tr>
<td class="style2">
</td>
<td align="left">
<asp:Button ID="Button1" class="btn-primary" runat="server" Text="Add"
Height="36px" Width="74px" onclick="Button1_Click" />
<asp:Button ID="Button2" class="btn-primary" runat="server" Text="Cancel"
Height="36px" Width="74px" PostBackUrl="~/districtDetails.aspx" />
</td>
</tr>
<tr>
<td class="style2">
</td>
<td align="left">
<asp:Label ID="Label2" runat="server" ForeColor="Red"></asp:Label>
</td>
</tr>
</table>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</fieldset>
</form>
</div><!--/span-->
</div><!--/row-->
</div>
</div>
</asp:Content>
It's because you're using an UpdatePanel, it will refresh everything inside it's <ContentTemplate>, which in your case has input[name="type"] inside it.
Because it's refreshed, the on('click', function() { isn't binding the current radiobutton with the name="type" anymore, thus make the click never triggered after you select one item inside the dropdown, what you need is to wrap the UpdatePanel only for things that you want to be refreshed or changed only, like this for your case:
<asp:UpdatePanel ID="updatepanel1" runat="server">
<ContentTemplate>
<tr>
<td align="left" class="style2">
MachID
</td>
<td align="left">
<asp:DropDownList ID="ddid" runat="server" AutoPostBack="True"
onselectedindexchanged="ddid_SelectedIndexChanged">
</asp:DropDownList>
</td>
</tr>
<tr>
<td align="left" class="style2">
<asp:Label ID="Empcode" runat="server" Text="EmpCode"></asp:Label>
</td>
<td align="left">
<asp:TextBox ID="txtname" runat="server"></asp:TextBox>
</td>
</tr>
</ContentTemplate>
</asp:UpdatePanel>
Other Way
Use the jQuery on click selector, you just need to change
$('input[name="type"]').on('click', function () {
if ($(this).val() == 'Experienced') {
$('#txtcomp').show();
$('#txtfrom').show();
$('#txtto').show();
}
too
$('.ui-accordion').on('click', 'input[name="type"]', function () {
if ($(this).val() == 'Experienced') {
$('#txtcomp').show();
$('#txtfrom').show();
$('#txtto').show();
}
The show function is k senstive. Try this:
$('#txtcomp,#txtfrom,#txtto').show();

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

How to add controls dynamically in .net?

I want to add controls dynamically
Code:
.aspx
<body>
<form id="form1" runat="server">
<asp:Label ID="lbl1" Text="Personal Information" Font-Size="Large" ForeColor="White" runat="server" Width="854px" BackColor="SteelBlue" style="margin-top: 0px" Height="60px"> </asp:Label>
<div id="div1" runat="server">
<asp:Panel ID="panelPersonal" runat="server">
<div id="divreg" runat="server">
<table id="tbl" runat="server">
<tr>
<td class="style8"> Visa Number:</td>
<td class="style20"> <asp:TextBox ID="txtUser" Width="160px" runat="server"/></td>
<td class="style22"> Country Name:</td>
<td class="style23"> <asp:DropDownList ID="dropCountry" Width="165px" runat="server"></asp:DropDownList></td>
</tr>
<tr>
<td class="style22"> Type of Visa:</td>
<td class="style23"> <asp:DropDownList ID="dropVisa" Width="165px" runat="server"> </asp:DropDownList></td>
<td class="style22"> Type of Entry:</td>
<td class="style23"> <asp:DropDownList ID="dropEntry" Width="165px" runat="server"></asp:DropDownList></td>
</tr>
<tr>
<td class="style8"> Expiry Date</td>
<td class="style20">
<%--<BDP:BasicDatePicker ID="BasicDatePicker4" runat="server" onselectionchanged="BasicDatePicker2_SelectionChanged" AutoPostBack="True" />--%>
</td>
</tr>
</table>
</div>
</asp:Panel>
<asp:Button ID="addnewtext" runat="server" Text="Add" onclick="addnewtext_Click" width="76px" />
</div>
</form>
Here I am using User control
.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="AddVisaControl.ascx.cs" EnableViewState="false" Inherits="Pyramid.AddVisaControl" %>
<div id="divreg" runat="server">
<table id="tbl" runat="server">
<tr>
<td> Visa Number:</td>
<td><asp:TextBox ID="txtUser" Width="160px" runat="server"/></td>
<td> Country Name:</td>
<td><asp:DropDownList ID="dropCountry" Width="165px" runat="server"></asp:DropDownList></td>
</tr>
<tr>
<td> Type of Visa:</td>
<td><asp:DropDownList ID="dropVisa" Width="165px" runat="server"></asp:DropDownList></td>
<td> Type of Entry:</td>
<td><asp:DropDownList ID="dropEntry" Width="165px" runat="server"></asp:DropDownList></td>
</tr>
<tr>
<td> Expiry Date</td>
<td>
</td>
</tr>
</table>
</div>
.aspx.cs
Here is the problem If I click add button one row is added successfully but when I close and open again previously added rows also coming.
I think the problem is static int i = 0;
Any other way is there?
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
}
static int i = 0;
protected void addnewtext_Click(object sender, EventArgs e)
{
i++;
for (int j = 0; j <= i; j++)
{
AddVisaControl ac = (AddVisaControl)Page.LoadControl("AddVisaControl.ascx");
PlaceHolder1.Controls.Add(ac);
PlaceHolder1.Controls.Add(new LiteralControl("<BR>"));
}
}
This is what I am getting
This is what I want, Like below image I want to do
Any ideas? Thanks in advance
can you use a repeater /gridview control in the place of place holder control ,i think that is the best method for your situvation
I recommend this solution. It is different from the code you are using but still very easy.
You can use a Repeater control
<asp:Repeater ID="rpt1" runat="server">
<ItemTemplate>
user control code goes here but first put it in a div(example id - div1) with `style="display:none"`
</ItemTemplate>
</asp:Repeater>
on the server side you do this
rpt1.DataSource = Utils.GetRptTable(4); // will add the code 4 times but it will not be visible
rpt1.DataBind();
Later in javascript on the page you can find the first div with id div1 that has style - display:none and show it. That way you will show the next "row" with fields.
Edit 1
If you can add all your fields in the user control in a single <tr> you don't need a div with style= display:none. You will just have to add this class="GridBody" to your <tbody> - like: <tbody class="GridBody">
Then you do this to the row:
<tr class="GridRow" id="row1" style="display: none">
...
</tr>
and the javascript to show the row is:
function addRow() {
var body = $(".GridBody");
var indexOfNextRow = $('tr[class="GridRow"][hidden="false"]').length;
var tr = $(".GridBody tr")[indexOfNextRow];
tr.style.display = 'table-row';
tr.setAttribute('hidden', 'false');
}

Controls does not exist in current context in ASP.Net CreateUserWizard

I am working on a project in Microsoft Visual Studio using an ASP.NET web application with code behind in C#. I added a CreateUserWizard and customized the form in step 1. From the events handler I put a CreatedUser handler into the codebehind to update database tables.
I want to pull the data values for the handler from the form, but the codebehind file can't see them for some reason. Help!
Main Page
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="PageControls" runat="server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="RightBox" runat="server">
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="SiteControl1" runat="server">
</asp:Content>
<asp:Content ID="Content5" ContentPlaceHolderID="SiteControl2" runat="server">
</asp:Content>
<asp:Content ID="Content6" ContentPlaceHolderID="SiteControl3" runat="server">
</asp:Content>
<asp:Content ID="Content7" ContentPlaceHolderID="CPMain" runat="server">
<center>
<asp:CreateUserWizard ID="CreateUserWizard1" runat="server"
CreateUserButtonText="Submit"
RequireEmail="False" OnCreatedUser="CreateUserWizard1_CreatedUser">
<WizardSteps>
<asp:CreateUserWizardStep ID="CreateUserWizardStep1" runat="server">
<ContentTemplate>
<table border="0" style="font-size: 100%">
<tr>
<td align="center" colspan="2" style="font-weight:
bold; color: white; background-color: #5d7b9d">
Register with Acme!
</td>
</tr>
<tr>
<td align="right">
<asp:Label ID="Label1" runat="server"
AssociatedControlID="UserName">
First Name:</asp:Label>
</td>
<td>
<asp:TextBox ID="FName" runat="server">
</asp:TextBox>
<asp:RequiredFieldValidator
ID="RequiredFieldValidator1" runat="server" ControlToValidate="FirstName"
ErrorMessage="First Name is required."
ToolTip="First Name is required." ValidationGroup="CreateUserWizard1">*
</asp:RequiredFieldValidator>
</td>
<tr>
<td align="right">
<asp:Label ID="Label2" runat="server">
Last Name:</asp:Label>
</td>
<td>
<asp:TextBox ID="LName" runat="server">
</asp:TextBox>
<asp:RequiredFieldValidator
ID="RequiredFieldValidator2" runat="server" ControlToValidate="LastName"
ErrorMessage="Last Name is required."
ToolTip="Last Name is required." ValidationGroup="CreateUserWizard1">*
</asp:RequiredFieldValidator>
</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="CreateUserWizard1">*
</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="CreateUserWizard1">*
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="right">
<asp:Label ID="ConfirmPasswordLabel"
runat="server" AssociatedControlID="ConfirmPassword">
Confirm Password:</asp:Label>
</td>
<td>
<asp:TextBox ID="ConfirmPassword"
runat="server" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator
ID="ConfirmPasswordRequired" runat="server" ControlToValidate="ConfirmPassword"
ErrorMessage="Confirm Password is
required." ToolTip="Confirm Password is required."
ValidationGroup="CreateUserWizard1">*
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="center" colspan="2">
<asp:CompareValidator ID="PasswordCompare"
runat="server" ControlToCompare="Password"
ControlToValidate="ConfirmPassword"
Display="Dynamic" ErrorMessage="The Password and Confirmation Password must match."
ValidationGroup="CreateUserWizard1">
</asp:CompareValidator>
</td>
</tr>
<tr>
<td align="center" colspan="2" style="color: red">
<asp:Literal ID="ErrorMessage" runat="server"
EnableViewState="False"></asp:Literal>
</td>
</tr>
<tr>
<td align="right">
<asp:Label ID="Label3" runat="server"
AssociatedControlID="UserName">
Role:</asp:Label>
</td>
<td>
<asp:DropDownList ID="RoleSelector"
runat="server">
<asp:ListItem
Value="Visitor">Visitor</asp:ListItem>
<asp:ListItem
Value="Employee">Employee</asp:ListItem>
<asp:ListItem Value="PM">Project
Manager</asp:ListItem>
<asp:ListItem Value="DM">Department
Manager</asp:ListItem>
<asp:ListItem Value="Director">IT
Director</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
</table>
</ContentTemplate>
</asp:CreateUserWizardStep>
<asp:CompleteWizardStep ID="CompleteWizardStep1" runat="server">
<ContentTemplate>
</ContentTemplate>
</asp:CompleteWizardStep>
</WizardSteps>
</asp:CreateUserWizard>
</center>
</asp:Content>
CodeBehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Principal;
namespace Acme
{
public partial class Register : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
{
RolesManager.InsertEmployee(FName.Text, LName.Text, RoleSelector.Value,
User.Identity);
}
}
}
I get these errors at compile time:
Error 1 The name 'FName' does not exist in the current context C:\MV_Training\Jan2013\C#Projects\AcmePresentation\AcmePresentation\Register.aspx.cs 20 41 AcmePresentation
Error 2 The name 'LName' does not exist in the current context C:\MV_Training\Jan2013\C#Projects\AcmePresentation\AcmePresentation\Register.aspx.cs 20 53 AcmePresentation
Error 3 The name 'RoleSelector' does not exist in the current context C:\MV_Training\Jan2013\C#Projects\AcmePresentation\AcmePresentation\Register.aspx.cs 20 65 AcmePresentation
and this from the browser:
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS1061: 'ASP.register_aspx' does not contain a definition for 'CreateUserWizard1_CreatedUser' and no extension method 'CreateUserWizard1_CreatedUser' accepting a first argument of type 'ASP.register_aspx' could be found (are you missing a using directive or an assembly reference?)
Source Error:
Line 16: <asp:Content ID="Content7" ContentPlaceHolderID="CPMain" runat="server">
Line 17: <center>
Line 18: <asp:CreateUserWizard ID="CreateUserWizard1" runat="server"
Line 19: CreateUserButtonText="Submit" RequireEmail="False"
Line 20: oncreateduser="CreateUserWizard1_CreatedUser">
Source File: c:\MV_Training\Jan2013\C#Projects\AcmePresentation\AcmePresentation\Register.aspx Line: 18
Thanks,
Bill
You want to cast controls explicitly something like this -
public void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
{
var fNameTextBox = (TextBox)CreateUserWizardStep1
.ContentTemplateContainer.FindControl("FName");
var lNameTextBox = (TextBox)CreateUserWizardStep1
.ContentTemplateContainer.FindControl("LName");
var usernameTextBox = (TextBox)CreateUserWizardStep1
.ContentTemplateContainer.FindControl("UserName");
MembershipUser user = Membership.GetUser(usernameTextBox.Text);
Guid userId = (Guid)user.ProviderUserKey;
}

Categories

Resources