Gridview UpdatePanel when update gridview disappear - c#

I got a gridview to show user data and a item hyperlink when click will populate the data on below table for admin to update.
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<fieldset>
<div style="float: left;">
<h2>
Members</h2>
</div>
<div style="float: right; padding-right: 30px;">
Create Member
</div>
<div style="clear: both;" />
<hr />
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" BackColor="White"
BorderColor="#CCCCCC" BorderStyle="None" DataKeyNames="UserID" BorderWidth="1px"
CellPadding="4" ForeColor="Black" GridLines="Horizontal" Width="886px" EnableSortingAndPagingCallbacks="true">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="First Name" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" />
<asp:BoundField DataField="email" HeaderText="Email" />
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:HyperLink ID="HyperLink2" runat="server" NavigateUrl='<%# "~/member.aspx?UserID="+ DataBinder.Eval(Container.DataItem,"UserID") %>'
Text='View'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
</ContentTemplate>
<Triggers>
<div class="formlabel">
Index :</div>
<div class="formlabel">
<asp:Label ID="userID" runat="server" Text=""></asp:Label></div>
<br />
<div class="formlabel">
Login Name :</div>
<asp:TextBox ID="username" runat="server" MaxLength="40"></asp:TextBox>
<asp:RequiredFieldValidator ControlToValidate="username" ID="RequiredFieldValidator1"
runat="server" ErrorMessage="Username can't be null" Display="None">
</asp:RequiredFieldValidator>
<cc1:ValidatorCalloutExtender ID="ValidatorCalloutExtender1" runat="server" TargetControlID="RequiredFieldValidator1" />
<asp:CustomValidator ID="CustomValidator6" runat="server" ControlToValidate="username"
Display="None" ErrorMessage="Username already exists." ClientValidationFunction="CheckUniqueness"
OnServerValidate="UserNameExistsValidator_ServerValidate"></asp:CustomValidator>
<cc1:ValidatorCalloutExtender ID="ValidatorCalloutExtender14" runat="server" PopupPosition="Right"
TargetControlID="CustomValidator6">
</cc1:ValidatorCalloutExtender>
<br />
<div class="formlabel">
Password :</div>
<asp:TextBox ID="password" runat="server" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ControlToValidate="password" ID="RequiredFieldValidator2"
runat="server" ErrorMessage="Password can't be null" Display="None">
</asp:RequiredFieldValidator>
<cc1:ValidatorCalloutExtender ID="ValidatorCalloutExtender2" runat="server" TargetControlID="RequiredFieldValidator2">
</cc1:ValidatorCalloutExtender>
<br />
<div class="formlabel">
First Name :</div>
<asp:TextBox ID="firstname" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ControlToValidate="firstname" ID="RequiredFieldValidator3"
runat="server" ErrorMessage="First Name can't be null" Display="None">
</asp:RequiredFieldValidator>
<cc1:ValidatorCalloutExtender ID="ValidatorCalloutExtender3" runat="server" TargetControlID="RequiredFieldValidator3">
</cc1:ValidatorCalloutExtender>
<br />
<div class="formlabel">
Last Name :</div>
<asp:TextBox ID="lastname" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ControlToValidate="lastname" ID="RequiredFieldValidator4"
runat="server" ErrorMessage="Last Name can't be null" Display="None">
</asp:RequiredFieldValidator>
<cc1:ValidatorCalloutExtender ID="ValidatorCalloutExtender4" runat="server" TargetControlID="RequiredFieldValidator4">
</cc1:ValidatorCalloutExtender>
<br />
<div class="formlabel">
Email :</div>
<asp:TextBox ID="email" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ControlToValidate="lastname" ID="RequiredFieldValidator5"
runat="server" ErrorMessage="Email can't be null" Display="None">
</asp:RequiredFieldValidator>
<cc1:ValidatorCalloutExtender ID="ValidatorCalloutExtender5" runat="server" TargetControlID="RequiredFieldValidator5">
</cc1:ValidatorCalloutExtender>
<asp:RegularExpressionValidator ID="REVEmail" runat="server" ControlToValidate="email"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*" ErrorMessage="Invalid Email"
Display="None"></asp:RegularExpressionValidator>
<cc1:ValidatorCalloutExtender ID="REVEmail_ValidatorCalloutExtender" runat="server"
TargetControlID="REVEmail">
</cc1:ValidatorCalloutExtender>
<br />
<br />
<asp:Label ID="msg" runat="server" Text=""></asp:Label>
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Update" />
<br />
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>
Below are my backend code:
if (Page.IsValid)
{
string id = Request.QueryString["UserID"];
string firstnamevalue = firstname.Text;
string lastnamevalue = lastname.Text;
string emailvalue = email.Text;
MySqlConnection connect = new MySqlConnection(connectionString);
MySqlCommand command = connect.CreateCommand();
command.CommandText = "Update user set Email = '" + emailvalue + "', FirstName ='" + firstnamevalue + "' , LastName ='" + lastnamevalue + "' WHERE UserID =" + id;
try
{
connect.Open();
command.Connection = connect;
command.ExecuteNonQuery();
GridView1.DataBind();
UpdatePanel2.Update();
}
catch
{
msg.Text = "Error Occured";
}
finally
{
connect.Close();
}
}
When I tried update the gridview will gone, may I know what is with my code?

Related

'username' does not exist in it's current context

The ID is inside the ItemTemplate and it cannot be found in the code file.
<form id="form1" runat="server">
<asp:SqlDataSource ID="searchresults" runat="server"
ConnectionString='<%$ ConnectionStrings:AgileDatabaseConnection %>'
SelectCommand=" SELECT [userID], [userName], [firstName],[lastName],[password], [email] FROM [Users] WHERE ([email] LIKE '%' + #email + '%')">
<selectparameters>
<asp:querystringparameter querystringfield="searchquery" name="email" type="String"></asp:querystringparameter>
</selectparameters>
</asp:SqlDataSource>
<asp:ListView ID="displayitems" runat="server" DataSourceID="searchresults">
<itemtemplate>
<asp:label runat="server" associatedcontrolid="projectOwner" cssclass="col-md-2 control-label">Project Owner:</asp:label>
<div class="col-md-10">
<asp:TextBox runat="server" ID="ProjectOwner" CssClass="form-control" /><br />
<asp:label runat="server" associatedcontrolid="projectOwner" cssclass="col-md-2 control-label">Scrum Master:</asp:label>
<div class="col-md-10">
<asp:SqlDataSource ID="ScrumMaster" runat="server" ConnectionString='<%$ ConnectionStrings:AgileDatabaseConnection %>' SelectCommand="SELECT userName FROM [Users]"></asp:SqlDataSource>
<asp:dropdownlist runat="server" id="usertype" DataSourceID="ScrumMaster" DataTextField="userName"></asp:dropdownlist><br />
</div>
</div>
<asp:label runat="server" cssclass="col-md-2 control-label">Email:</asp:label>
<asp:Label Text='<%#Eval("email") %>' runat="server" ID="emaillabel" /><br />
<asp:label runat="server" cssclass="col-md-2 control-label">UserName:</asp:label>
<asp:Label Text='<%#Eval("userName") %>' runat="server" ID="username" /><br />
<asp:label runat="server" cssclass="col-md-2 control-label">UserID:</asp:label>
<asp:Label runat="server" Text='<%#Eval("userID") %>' ID="UserID" CssClass="form-control" />
<br />
<div class="actions"></div>
<asp:Button Text="Add" runat="server" class="btn pull-right" ID="uploadbutton" OnClick="add_Click"></asp:Button>
</div>
</itemtemplate>
</asp:ListView>
<emptydatatemplate>
<span>No users match <asp:Label Text='' runat="server" ID="email" /> .</span>
</emptydatatemplate>
</form>
C# says it can't find 'userName'. Here's my backend code:
string ownerName = ProjectOwner.Text;
string IDuser = username.Text;
string IDdata = Session["userID"].ToString();
How do I get the userName value through?
The problem is that ListView can return more then one item, so code behind doesn't know about which of the itens controls (username and ProjectOwner) are you talking about.
If you want to do the same thing for EACH item, you can do like this:
protected void displayitems_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
string ownerName = ((TextBox)e.Item.FindControl("ProjectOwner")).Text;
string IDuser = ((Label)e.Item.FindControl("username").Text;
string IDdata = Session["userID"].ToString();
}
}

using SESSIONS passing values to another page

I am stuck on passing values from a form on one page to (confirm.aspx) another page. Would someone help me out with this? I am not looking for some one to code my program because I have done much of the work already. Here is what I have, Default.aspx as three values that I need to pass to Confirm.aspx. This is what I have for the Default.aspx.
<form id="form1" runat="server">
<h1>Price quotation</h1>
<label>Sales price</label>
<asp:TextBox ID="txtSalesPrice" runat="server" CssClass="entry">100</asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtSalesPrice" Display="Dynamic" ErrorMessage="RequiredFieldValidator" CssClass="validator">Required</asp:RequiredFieldValidator>
<asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="txtSalesPrice" Display="Dynamic" MaximumValue="1000" MinimumValue="10" Type="Double" CssClass="validator">Must be from 10 to 1000</asp:RangeValidator><br /><br />
<label>Discount percent</label>
<asp:TextBox ID="txtDiscountPercent" runat="server" CssClass="entry">20</asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtDiscountPercent" Display="Dynamic" ErrorMessage="RequiredFieldValidator" CssClass="validator">Required</asp:RequiredFieldValidator>
<asp:RangeValidator ID="RangeValidator2" runat="server" ControlToValidate="txtDiscountPercent" Display="Dynamic" MaximumValue="50" MinimumValue="10" Type="Double" CssClass="validator">Must be from 10 to 50</asp:RangeValidator><br />
<label>Discount amount</label>
<asp:Label ID="lblDiscountAmount" runat="server" CssClass="result" ></asp:Label><br /><br />
<label>Total price</label>
<asp:Label ID="lblTotalPrice" runat="server" CssClass="result" ></asp:Label><br /><br />
<asp:Button ID="btnCalculate" runat="server" Text="Calculate" OnClick="btnCalculate_Click" CssClass="button" />
<asp:Button ID="ConfirmButton" runat="server" CssClass="button" Text="Confirm" PostBackUrl="~/Confirm.aspx" OnClick="ConfirmButton_Click" />
<p><asp:Label ID="lblMessage" runat="server" EnableViewState="false" /></p>
</form>
Code Behind the Default.aspx
protected void ConfirmButton_Click(object sender, EventArgs e)
{
Session["Sales"] = txtSalesPrice.Text;
Response.Redirect("Confirm.aspx");
Session["Amt"] = lblDiscountAmount.Text;
Response.Redirect("Confirm.aspx");
Session["Total"] = lblTotalPrice.Text;
Response.Redirect("Confirm.aspx");
}
Confirm.aspx
<form id="form1" runat="server">
<h1>Quotation confirmation</h1>
<label>Sales price</label><asp:Label ID="lblSalesPrice" runat="server" CssClass="result"></asp:Label><%=Session["Sales"] %><br /><br />
<label>Discount amount</label><asp:Label ID="lblDiscountAmount" runat="server" CssClass="result"><%=Session["Amt"] %></asp:Label><br /><br />
<label>Total price</label><asp:Label ID="lblTotalPrice" runat="server" CssClass="result"><%=Session["Price"] %></asp:Label><br />
<h2>Send confirmation to</h2>
<label>Name</label>
<asp:TextBox ID="txtName" runat="server" CssClass="entry"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtName" Display="Dynamic" ErrorMessage="RequiredFieldValidator" CssClass="validator">Required</asp:RequiredFieldValidator><br />
<label>Email address</label>
<asp:TextBox ID="txtEmail" runat="server" CssClass="entry"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtEmail" Display="Dynamic" ErrorMessage="RequiredFieldValidator" CssClass="validator">Required</asp:RequiredFieldValidator><br />
<asp:Button ID="btnSubmit" runat="server" Text="Send Quotation" CssClass="button" OnClick="btnSubmit_Click" />
<asp:Button ID="btnReturn" runat="server" Text="Return" PostBackUrl="~/Default.aspx" CausesValidation="false" CssClass="button" OnClick="btnReturn_Click" />
<p><asp:Label ID="lblMessage" runat="server" ViewStateMode="Enabled" /></p>
</form>
If someone would take the time out and review what I have here. I would appreciate. There is nothing pertinent on the code behind on the Confirm.aspx.cs.
Code behind default.aspx
protected void ConfirmButton_Click(object sender, EventArgs e)
{
Session["Sales"] = txtSalesPrice.Text;
Session["Amt"] = lblDiscountAmount.Text;
Session["Total"] = lblTotalPrice.Text;
Response.Redirect("Confirm.aspx");
}
And you get value in another page like this
In .cs
txtSales.text = Session["Sales"];
In .aspx
<asp:TextBox ID="txtSales" runat="server" Text='<%# Session["Sales"] %>' >

How to expand Jquery Slider Panel programatically?

I have JQuery Silder panel for Login | Register option. for referencing i have include demo of this slider Jquery Login | Register Slider Panel
the actually problem was how to expand programatically this slider when located Literal control have value in Login Section or Register New account section. for understanding this problem i putting my design code.
<asp:Panel ID="Panel_Login_Register" runat="server" CssClass="Panel_Slide">
<div id="toppanel">
<div id="panel">
<div class="content clearfix">
<asp:Panel ID="Panel_Welcome" runat="server" CssClass="left">
<h1>Welcome to Om Investment</h1>
<p class="grey">Om Investment Stock Market Research Trading & Advisory, the most successful market
trading team and has predicted the market direction always ahead of others, our
powerful and high volume Market Gains trading team will deliver high returns to
the Capital invested by clients, We have a consistent success ratio genuine more than
80% in every type of Market.</p>
</asp:Panel>
<asp:Panel ID="Panel_Login" runat="server" CssClass="left" Width="200px" DefaultButton="btnlogin">
<h1>Member Login</h1>
<asp:Label ID="Label2" runat="server" Text="Username:" CssClass="grey" AssociatedControlID="txtusername"></asp:Label>
<cc1:TextBoxWatermarkExtender ID="TextBoxWatermarkExtender4" runat="server" TargetControlID="txtusername" WatermarkText="Enter username here"/>
<asp:TextBox ID="txtusername" runat="server" CssClass="field" ValidationGroup="Login"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="<span style='color:Black'><b>Required Field Missing</b><br />Username is required.</span>"
ControlToValidate="txtusername" ValidationGroup="Login" Display="None" SetFocusOnError="true"></asp:RequiredFieldValidator>
<cc1:ValidatorCalloutExtender ID="ValidatorCalloutExtender2" runat="server" TargetControlID="RequiredFieldValidator2"
Width="200px" HighlightCssClass="highlight" WarningIconImageUrl="images/1329542890_dialog-warning.png"
CloseImageUrl="images/close.gif">
</cc1:ValidatorCalloutExtender>
<asp:Label ID="Label3" runat="server" Text="Password:" CssClass="grey" AssociatedControlID="txtpassword"></asp:Label>
<cc1:TextBoxWatermarkExtender ID="TextBoxWatermarkExtender12" runat="server" TargetControlID="txtpassword"
WatermarkText="123456789"/>
<asp:TextBox ID="txtpassword" runat="server" CssClass="field" ValidationGroup="Login" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="<span style='color:Black'><b>Required Field Missing</b><br />Password is required.</span>"
ControlToValidate="txtpassword" ValidationGroup="Login" Display="None"></asp:RequiredFieldValidator>
<cc1:ValidatorCalloutExtender ID="ValidatorCalloutExtender3" runat="server" TargetControlID="RequiredFieldValidator3"
Width="200px" HighlightCssClass="highlight" WarningIconImageUrl="images/1329542890_dialog-warning.png"
CloseImageUrl="images/close.gif">
</cc1:ValidatorCalloutExtender><br />
<asp:CheckBox ID="chk_remember" runat="server"/> <asp:Label ID="Label4" runat="server" Text="Remeber Me ?" CssClass="grey"></asp:Label>
<div class="clear"></div>
<asp:Button ID="btnlogin" runat="server" Text="Login" CssClass="bt_login" ValidationGroup="Login" OnClick="btnlogin_Click" />
<a class="lost-pwd" href="password_recover.aspx"> Lost your password ?</a>
<div class="clear"></div>
<p class="grey"><asp:Literal ID="ltr_error" runat="server"></asp:Literal></p>
</asp:Panel>
<asp:Panel ID="Panel_Register" runat="server" CssClass="left right" DefaultButton="btn_register" Width="356px">
<h1>Create New Account</h1>
<p class="grey">(All the fields are compulsory)</p>
<table><tr><td><asp:Label id="Label6" runat="server" Text="Your Name*" AssociatedControlID="txtname" CssClass="grey"></asp:Label> <cc1:TextBoxWatermarkExtender id="TextBoxWatermarkExtender5" watermarkText="Enter your name" runat="server" TargetControlID="txtname">
</cc1:TextBoxWatermarkExtender> <cc1:FilteredTextBoxExtender id="FilteredTextBoxExtender2" runat="server" TargetControlID="txtname" ValidChars=" ,." FilterType="UppercaseLetters,LowercaseLetters,Custom">
</cc1:FilteredTextBoxExtender></td></tr>
<tr><td><asp:TextBox id="txtname" runat="server" CssClass="field" ValidationGroup="SignUp" MaxLength="50"></asp:TextBox> <asp:RequiredFieldValidator id="RequiredFieldValidator5" runat="server" ValidationGroup="SignUp" SetFocusOnError="true" Display="None" ControlToValidate="txtname" ErrorMessage="<span style='color:Black'><b>Required Field Missing</b><br />Your name is required.</span>"></asp:RequiredFieldValidator> <cc1:ValidatorCalloutExtender id="ValidatorCalloutExtender4" runat="server" TargetControlID="RequiredFieldValidator5" Width="200px" CloseImageUrl="images/close.gif" WarningIconImageUrl="images/1329542890_dialog-warning.png" HighlightCssClass="highlight">
</cc1:ValidatorCalloutExtender></td></tr>
<tr><td><asp:Label id="Label7" runat="server" Text="Your Username*" AssociatedControlID="txtusername1" CssClass="grey"></asp:Label> <cc1:TextBoxWatermarkExtender id="TextBoxWatermarkExtender6" watermarkText="Enter your username" runat="server" TargetControlID="txtusername1">
</cc1:TextBoxWatermarkExtender> <cc1:FilteredTextBoxExtender id="FilteredTextBoxExtender3" runat="server" TargetControlID="txtusername" FilterType="UppercaseLetters,LowercaseLetters,Numbers,Custom">
</cc1:FilteredTextBoxExtender></td></tr>
<tr><td><asp:TextBox id="txtusername1" runat="server" CssClass="field" ValidationGroup="SignUp" MaxLength="50"></asp:TextBox><asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="txtusername1" OnServerValidate="CustomValidator1_ServerValidate" SetFocusOnError="True" ValidationGroup="SignUp" CssClass="grey" ErrorMessage="<span style='color:Gray'>Username is already exist</span>"></asp:CustomValidator></td></tr>
<tr><td><asp:RequiredFieldValidator id="RequiredFieldValidator6" runat="server" ValidationGroup="SignUp" SetFocusOnError="true" Display="None" ControlToValidate="txtusername1" ErrorMessage="<span style='color:Black'><b>Required Field Missing</b><br />Your username is required.</span>"></asp:RequiredFieldValidator> <cc1:ValidatorCalloutExtender id="ValidatorCalloutExtender7" runat="server" TargetControlID="RequiredFieldValidator6" Width="200px" CloseImageUrl="images/close.gif" WarningIconImageUrl="images/1329542890_dialog-warning.png" HighlightCssClass="highlight">
</cc1:ValidatorCalloutExtender></td></tr>
<tr><td><asp:Label id="Label9" runat="server" Text="Your Account Password*" AssociatedControlID="txtpass" CssClass="grey"></asp:Label> <cc1:FilteredTextBoxExtender id="FilteredTextBoxExtender4" runat="server" TargetControlID="txtpass" ValidChars="." FilterType="UppercaseLetters,LowercaseLetters,Numbers,Custom" InvalidChars=" ,'">
</cc1:FilteredTextBoxExtender> <cc1:TextBoxWatermarkExtender id="TextBoxWatermarkExtender7" watermarkText="1234567890" runat="server" TargetControlID="txtpass">
</cc1:TextBoxWatermarkExtender></td></tr>
<tr><td><asp:TextBox id="txtpass" runat="server" CssClass="field" ValidationGroup="SignUp" MaxLength="15" TextMode="Password"></asp:TextBox> <cc1:PasswordStrength id="PasswordStrength1" runat="server" TargetControlID="txtpass" RequiresUpperAndLowerCaseCharacters="false" MinimumSymbolCharacters="0" MinimumNumericCharacters="0" StrengthStyles="TextIndicator_TextBox1_Strength1;TextIndicator_TextBox1_Strength2;TextIndicator_TextBox1_Strength3;TextIndicator_TextBox1_Strength4;TextIndicator_TextBox1_Strength5" TextStrengthDescriptions="Very Poor;Weak;Average;Strong;Excellent" HelpStatusLabelID="TextBox1_HelpLabel" PrefixText="Strength:" PreferredPasswordLength="10" StrengthIndicatorType="Text" DisplayPosition="RightSide"></cc1:PasswordStrength> <asp:RequiredFieldValidator id="RequiredFieldValidator7" runat="server" ValidationGroup="SignUp" SetFocusOnError="true" Display="None" ControlToValidate="txtpass" ErrorMessage="<span style='color:Black'><b>Required Field Missing</b><br />Your account password is required.</span>"></asp:RequiredFieldValidator> <cc1:ValidatorCalloutExtender id="ValidatorCalloutExtender8" runat="server" TargetControlID="RequiredFieldValidator7" Width="200px" CloseImageUrl="images/close.gif" WarningIconImageUrl="images/1329542890_dialog-warning.png" HighlightCssClass="highlight">
</cc1:ValidatorCalloutExtender></td></tr>
<tr><td><asp:Label id="Label10" runat="server" Text="Confirm Password*" AssociatedControlID="txtcpass" CssClass="grey"></asp:Label><cc1:TextBoxWatermarkExtender id="TextBoxWatermarkExtender8" watermarkText="1234567890" runat="server" TargetControlID="txtcpass">
</cc1:TextBoxWatermarkExtender> <cc1:FilteredTextBoxExtender id="FilteredTextBoxExtender5" runat="server" TargetControlID="txtpass" ValidChars="." FilterType="UppercaseLetters,LowercaseLetters,Numbers,Custom" InvalidChars=" ,'">
</cc1:FilteredTextBoxExtender></td></tr>
<tr><td><asp:TextBox id="txtcpass" runat="server" CssClass="field" ValidationGroup="SignUp" MaxLength="15" TextMode="Password"></asp:TextBox> <asp:RequiredFieldValidator id="RequiredFieldValidator8" runat="server" ValidationGroup="SignUp" SetFocusOnError="true" Display="None" ControlToValidate="txtcpass" ErrorMessage="<span style='color:Black'><b>Required Field Missing</b><br />Confirm password is required.</span>"></asp:RequiredFieldValidator> <asp:CompareValidator id="CompareValidator1" runat="server" ValidationGroup="SignUp" SetFocusOnError="true" Display="None" ControlToValidate="txtcpass" ErrorMessage="<span style='color:Black'><b>Entered Field is Invalid</b><br />Your new password and confirm password doesn't mathched.</span>" ControlToCompare="txtpass"></asp:CompareValidator> <cc1:ValidatorCalloutExtender id="ValidatorCalloutExtender9" runat="server" TargetControlID="RequiredFieldValidator8" Width="200px" CloseImageUrl="images/close.gif" WarningIconImageUrl="images/1329542890_dialog-warning.png" HighlightCssClass="highlight">
</cc1:ValidatorCalloutExtender> <cc1:ValidatorCalloutExtender id="ValidatorCalloutExtender11" runat="server" TargetControlID="CompareValidator1" Width="200px" CloseImageUrl="images/close.gif" WarningIconImageUrl="images/1329542890_dialog-warning.png" HighlightCssClass="highlight">
</cc1:ValidatorCalloutExtender></td></tr>
<tr><td><asp:Label id="Label12" runat="server" Text="Your Birth Date*" AssociatedControlID="txtbdate" CssClass="grey"></asp:Label> <cc1:TextBoxWatermarkExtender id="TextBoxWatermarkExtender10" watermarkText="Enter your birthdate" runat="server" TargetControlID="txtbdate">
</cc1:TextBoxWatermarkExtender></td></tr>
<tr><td><asp:TextBox id="txtbdate" runat="server" CssClass="field" ValidationGroup="SignUp"></asp:TextBox> <asp:RequiredFieldValidator id="RequiredFieldValidator10" runat="server" ValidationGroup="SignUp" SetFocusOnError="true" Display="None" ControlToValidate="txtbdate" ErrorMessage="<span style='color:Black'><b>Required Field Missing</b><br />Your birthdate is required.</span>"></asp:RequiredFieldValidator> <asp:RegularExpressionValidator id="RegularExpressionValidator3" runat="server" ValidationGroup="SignUp" SetFocusOnError="true" Display="None" ControlToValidate="txtbdate" ErrorMessage="<span style='color:Black'><b>Entered Field is Invalid</b><br/>Birth date format should be like: DD/MM/yyyy</span>" ValidationExpression="^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$"></asp:RegularExpressionValidator> <cc1:CalendarExtender id="CalendarExtender1" runat="server" TargetControlID="txtbdate" PopupButtonID="img_cal" Format="dd/MM/yyyy">
</cc1:CalendarExtender> <cc1:MaskedEditExtender id="MaskedEditExtender5" runat="server" TargetControlID="txtbdate" ErrorTooltipEnabled="True" AcceptNegative="Left" DisplayMoney="Left" MaskType="Date" OnInvalidCssClass="MaskedEditError" OnFocusCssClass="MaskedEditFocus" MessageValidatorTip="true" Mask="99/99/9999"></cc1:MaskedEditExtender> <cc1:ValidatorCalloutExtender id="ValidatorCalloutExtender13" runat="server" TargetControlID="RequiredFieldValidator10" Width="200px" CloseImageUrl="images/close.gif" WarningIconImageUrl="images/1329542890_dialog-warning.png" HighlightCssClass="highlight">
</cc1:ValidatorCalloutExtender> <cc1:ValidatorCalloutExtender id="ValidatorCalloutExtender14" runat="server" TargetControlID="RegularExpressionValidator3" Width="200px" CloseImageUrl="images/close.gif" WarningIconImageUrl="images/1329542890_dialog-warning.png" HighlightCssClass="highlight">
</cc1:ValidatorCalloutExtender></td></tr>
<tr><td><asp:Label id="Label11" runat="server" Text="Your e-mail*" AssociatedControlID="txtemail" CssClass="grey"></asp:Label><cc1:TextBoxWatermarkExtender id="TextBoxWatermarkExtender9" watermarkText="Enter your email" runat="server" TargetControlID="txtemail">
</cc1:TextBoxWatermarkExtender></td></tr>
<tr>
<td><asp:TextBox id="txtemail" runat="server" CssClass="field" ValidationGroup="SignUp" MaxLength="50"></asp:TextBox><asp:CustomValidator ID="CustomValidator2" runat="server" ValidationGroup="SignUp" ControlToValidate="txtemail" SetFocusOnError="true" OnServerValidate="CustomValidator2_ServerValidate" CssClass="grey" ErrorMessage="<span style='color:Gray'>Email is already exist</span>"></asp:CustomValidator></td></tr>
<tr><td><asp:RequiredFieldValidator id="RequiredFieldValidator9" runat="server" ValidationGroup="SignUp" SetFocusOnError="true" Display="None" ControlToValidate="txtemail" ErrorMessage="<span style='color:Black'><b>Required Field Missing</b><br />Your email is required.</span>"></asp:RequiredFieldValidator> <asp:RegularExpressionValidator id="RegularExpressionValidator2" runat="server" ValidationGroup="SignUp" SetFocusOnError="true" Display="None" ControlToValidate="txtemail" ErrorMessage="<span style='color:Black'><b>Entered Field is Invalid</b><br/>Email format should be like: name#domain.com</span>" ValidationExpression="^[\w-\.]{1,}\#([\da-zA-Z-]{1,}\.){1,}[\da-zA-Z-]{2,6}$"></asp:RegularExpressionValidator> <cc1:ValidatorCalloutExtender id="ValidatorCalloutExtender10" runat="server" TargetControlID="RequiredFieldValidator9" Width="200px" CloseImageUrl="images/close.gif" WarningIconImageUrl="images/1329542890_dialog-warning.png" HighlightCssClass="highlight">
</cc1:ValidatorCalloutExtender> <cc1:ValidatorCalloutExtender id="ValidatorCalloutExtender12" runat="server" TargetControlID="RegularExpressionValidator2" Width="200px" CloseImageUrl="images/close.gif" WarningIconImageUrl="images/1329542890_dialog-warning.png" HighlightCssClass="highlight">
</cc1:ValidatorCalloutExtender></td></tr>
<tr><td><asp:Label id="Label13" runat="server" Text="Your Phone no*" AssociatedControlID="txtphoneno" CssClass="grey"></asp:Label> <cc1:TextBoxWatermarkExtender id="TextBoxWatermarkExtender11" watermarkText="Enter your phone no" runat="server" TargetControlID="txtphoneno">
</cc1:TextBoxWatermarkExtender> <cc1:FilteredTextBoxExtender id="FilteredTextBoxExtender6" runat="server" TargetControlID="txtphoneno" FilterType="Numbers">
</cc1:FilteredTextBoxExtender></td></tr>
<tr>
<td><asp:TextBox id="txtphoneno" runat="server" CssClass="field" ValidationGroup="SignUp" MaxLength="10"></asp:TextBox><asp:CustomValidator ID="CustomValidator3" runat="server" ValidationGroup="SignUp" ControlToValidate="txtphoneno" SetFocusOnError="true" OnServerValidate="CustomValidator3_ServerValidate" CssClass="grey" ErrorMessage="<span style='color:Gray'>Phone no is already exist</span>"></asp:CustomValidator></td>
</tr>
<tr><td><asp:RequiredFieldValidator id="RequiredFieldValidator11" runat="server" ValidationGroup="SignUp" SetFocusOnError="true" Display="None" ControlToValidate="txtphoneno" ErrorMessage="<span style='color:Black'><b>Required Field Missing</b><br />Your phone no is required.</span>"></asp:RequiredFieldValidator><asp:RegularExpressionValidator id="RegularExpressionValidator4" runat="server" ValidationGroup="SignUp" SetFocusOnError="true" Display="None" ControlToValidate="txtphoneno" ErrorMessage="<span style='color:Black'><b>Entered Field is Invalid</b><br/>Phone no format should like : 9000000098<br/> +91 Not Needed<span>" ValidationExpression="^((\\+91-?)|0)?[0-9]{10}$"></asp:RegularExpressionValidator> <cc1:ValidatorCalloutExtender id="ValidatorCalloutExtender15" runat="server" TargetControlID="RequiredFieldValidator11" Width="200px" CloseImageUrl="images/close.gif" WarningIconImageUrl="images/1329542890_dialog-warning.png" HighlightCssClass="highlight">
</cc1:ValidatorCalloutExtender> <cc1:ValidatorCalloutExtender id="ValidatorCalloutExtender16" runat="server" TargetControlID="RegularExpressionValidator4" Width="200px" CloseImageUrl="images/close.gif" WarningIconImageUrl="images/1329542890_dialog-warning.png" HighlightCssClass="highlight">
</cc1:ValidatorCalloutExtender></td></tr>
<tr><td><asp:Button ID="btn_register" runat="server" Text="Register" ValidationGroup="SignUp" CssClass="bt_register" OnClick="btn_register_Click"/></td></tr>
</table>
<div class="clear"></div>
<p class="grey"><asp:Literal ID="ltr_message2" runat="server"></asp:Literal></p>
</asp:Panel>
</div>
</div>
<div class="tab">
<ul class="login">
<li class="left"> </li>
<li>Hello Guest!</li><li class="sep">|</li><li id="toggle">
<a id="open" class="open" href="#">Log In | Register</a>
<a id="close" style="display: none;" class="close" href="#">Close Panel</a>
</li>
<li class="right"> </li>
</ul>
</div>
</div>
</asp:Panel>
this slider works fine but i have no idea to how to auto expand this panel if one of the Literal have value.
In Register New Account panel i have also custome validators also i have to found the way to expand this panel if one the three custome validator throws Error message.
For details referencing i have also include js/slide.js file content:
$(document).ready(function() {
// Expand Panel
$("#open").click(function(){
$("div#panel").slideDown("slow");
});
// Collapse Panel
$("#close").click(function(){
$("div#panel").slideUp("slow");
});
// Switch buttons from "Log In | Register" to "Close Panel" on click
$("#toggle a").click(function () {
$("#toggle a").toggle();
});
});
_____________________Updated Code_____________________
this code is about how i append my custome error to literal control
protected void btnlogin_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
using (SqlConnection conn = Util.GetConnection())
{
conn.Open();
SqlCommand cmd = new SqlCommand("sp_CheckUserAccount", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#UserName", SqlDbType.VarChar).Value = txtusername.Text.Trim();
cmd.Parameters.Add("#pass", SqlDbType.VarChar).Value = txtpassword.Text.Trim();
cmd.Parameters.Add("#Error", SqlDbType.NVarChar, 100).Direction = ParameterDirection.Output;
SqlParameter sqlParam = cmd.Parameters.Add("#Return Value", SqlDbType.Int);
sqlParam.Direction = System.Data.ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
int returnValue = (int)cmd.Parameters["#Return Value"].Value;
if (returnValue == 1)
{
if (chk_remember.Checked == true)
{
conn.Close();
cmd.Dispose();
conn.Open();
SqlCommand cmd1 = new SqlCommand("sp_Read_User_Type", conn);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.Add(new SqlParameter("#Userid", SqlDbType.VarChar, 50, "Id"));
cmd1.Parameters["#Userid"].Value = txtusername.Text.Trim();
SqlDataReader reader = cmd1.ExecuteReader();
while (reader.Read())
{
if (reader["Type_name"].ToString() == "Admin")
{
Response.Cookies["UName"].Value = txtusername.Text;
Response.Cookies["PWD"].Value = txtpassword.Text;
Response.Cookies["UName"].Expires = DateTime.Now.AddMonths(2);
Response.Cookies["PWD"].Expires = DateTime.Now.AddMonths(2);
Session["username"] = reader["Id"].ToString();
Response.Redirect("~/Admin/Admin_Landing_page.aspx");
}
else
{
Response.Cookies["UName"].Value = txtusername.Text;
Response.Cookies["PWD"].Value = txtpassword.Text;
Response.Cookies["UName"].Expires = DateTime.Now.AddMonths(2);
Response.Cookies["PWD"].Expires = DateTime.Now.AddMonths(2);
Session["username"] = reader["Id"].ToString();
Response.Redirect("~/EndUser/myhome.aspx");
}
}
reader.Close();
}
else
{
Response.Cookies["UName"].Expires = DateTime.Now.AddMonths(-1);
Response.Cookies["PWD"].Expires = DateTime.Now.AddMonths(-1);
conn.Close();
cmd.Dispose();
conn.Open();
SqlCommand cmd1 = new SqlCommand("sp_Read_User_Type", conn);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.Add(new SqlParameter("#Userid", SqlDbType.VarChar, 50, "Id"));
cmd1.Parameters["#Userid"].Value = txtusername.Text.Trim();
SqlDataReader reader = cmd1.ExecuteReader();
while (reader.Read())
{
if (reader["Type_name"].ToString() == "Admin")
{
Session["username"] = reader["Id"].ToString();
Response.Redirect("~/Admin/Admin_Landing_page.aspx");
}
else
{
Session["username"] = reader["Id"].ToString();
Response.Redirect("~/EndUser/myhome.aspx");
}
}
reader.Close();
}
}
else
{
ltr_error.Text = (string)cmd.Parameters["#Error"].Value; }
}
}
}
http://www.roorkichap.com/sliding-login-panel-built-with-jquery-asp-net-vb-net-and-sql-server-2000/
download the source code and check out
Updated version:
Literal doesn't generate any tag on page. Therefore you need to set id for tag that wrap your Literal. (or something more suitable for you)
<p id="p_error" class="grey"><asp:Literal ID="ltr_error" runat="server"></asp:Literal></p>
After that you can use js for check any text.
$(document).ready(function() {
if ($("#p_error").text() != "") //choose condition more suitable for you
$("div#panel").slideDown("slow");
});

Panel visibilty on/off toggle effect not working

I've a got ListBox called lbxUpcommingEvents. When the index is changed the event handler is fired to check for duplicate records. If duplicates are not found, a panel called pnlAction inside a formview is turned on by the way of display style. If dups are found another panel pnlActionCancel is turned on and the oter is tuned off. Basically a toogle effect.
I've tried the visible property, viewstate property, but it does not work and I can't figure it out so once again, I seek wizdom from the collective. Here is my code.
protected void lbxUpcommingEvents_OnSelectedIndexChanged(object sender, EventArgs e)
{
pnlEventsSignUp.Visible = true;
string _selectedItemValue = lbxUpcommingEvents.SelectedValue.ToString();
int _eventid = Convert.ToInt32(_selectedItemValue);
Guid _memberId = Guid.Empty;
_memberId = new Guid(Session["myId"].ToString());
// Check for existing signup
EventsMemberSignup _createSingup = new EventsMemberSignup();
dsEventsSingupTableAdapters.MemberEventsTableAdapter da = new dsEventsSingupTableAdapters.MemberEventsTableAdapter();
dsEventsSingup.MemberEventsDataTable dt = da.GetDataForDupCheck(_memberId, _eventid);
if (dt.Rows.Count == 1)
{
Panel pnlAction = (Panel)(fvEventSignUp.FindControl("pnlAction"));
//pnlAction.Visible = false;
pnlAction.Style.Add("display","none");
Panel pnlActionCancel = (Panel)(fvEventSignUp.FindControl("pnlActionCancel"));
//pnlActionCancel.Visible = true;
pnlActionCancel.Style.Remove("display");
}
else
{
Panel pnlActionCancel = (Panel)(fvEventSignUp.FindControl("pnlActionCancel"));
//pnlActionCancel.Visible = false;
pnlActionCancel.Style.Add("display", "none");
Panel pnlAction = (Panel)(fvEventSignUp.FindControl("pnlAction"));
//pnlAction.Visible = true;
pnlAction.Style.Remove("display");
}
}
<div id="columnleft">
<a name="content_start" id="content_start"></a>
<div class="leftblock">
<h2>Events Signup</h2>
<p>
</p>
<h3> Upcomming Events</h3>
<p>
<asp:ListBox ID="lbxUpcommingEvents" runat="server" DataSourceID="odsUpcommingEvents"
Rows="6" DataTextField="Title" DataValueField="id" AutoPostBack="true"
Width="206px" OnSelectedIndexChanged="lbxUpcommingEvents_OnSelectedIndexChanged" />
</p>
<h3> Members Attending</h3>
<p>
<asp:DataGrid ID="lboxSignedUpMembers" runat="server" DataSourceID="odsSignedUpMembers"
AutoPostBack="true" AutoGenerateColumns="false" RowStyle-CssClass="gridview" AlternatingRowStyle-CssClass="altbgcolor"
Width="206px" onselectedindexchanged="lboxSignedUpMembers_SelectedIndexChanged" CssClass="gridview"
GridLines="None" BorderStyle="Solid" BorderWidth="1" BorderColor="Black" >
<AlternatingItemStyle BackColor="White" />
<Columns>
<asp:BoundColumn DataField="Name" />
<asp:BoundColumn DataField="Title" />
<asp:TemplateColumn >
<ItemTemplate>
<asp:Label runat="server" ID="lblDate" Text='<%# Eval("StartTime", "{0:d}") %>' />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
</p>
</div>
</div>
</td>
<td align="left" >
<!--Start of right column-->
<div id="columnright">
<div class="rightblock">
<asp:Panel ID="pnlEventsSignUpTitle" runat="server" CssClass="actionbuttons">
<h2>Select an Event to Signup</h2>
</asp:Panel>
<asp:Label runat="server" ID="lblNote" ForeColor="#cc0000" Font-Bold="true" />
</div>
<div class="rightblock">
<asp:Panel runat="server" ID="pnlEventsSignUp" visible="false">
<div class="dashedline" ></div>
<asp:FormView ID="fvEventSignUp" runat="server" DataSourceID="ObjectDataSource1"
DataKeyNames="id" Width="100%" >
<ItemTemplate>
<h2>
<asp:HiddenField runat="server" ID="hfEventID" Value='<%# Eval("id") %>' />
<asp:Label Text='<%# Eval("title") %>' runat="server" ID="titleLabel" />
</h2>
<div class="itemdetails">
<br />
location:
<h3>
<asp:Label ID="locationLabel" runat="server" Text='<%# ShowLocationLink(Eval("locationname"),Eval("location")) %>' />
</h3>
<p>
<asp:Label Text='<%# Eval("starttime","{0:D}") %>' runat="server" ID="itemdateLabel" CssClass="GeneralText" />
<asp:Label Text='<%# ShowDuration(Eval("starttime"),Eval("endtime")) %>' runat="server" ID="Label1" CssClass="GeneralText" />
</p>
</div>
<div class="downloadevent">
<a href="#">
<img src="images/icon_download_event.gif" alt="Download this event to your personal calendar"
width="15" height="26" /></a><a href='<%# "events_download.ashx?EventID=" + Convert.ToString(Eval("id")) %>'>Add
this event to your personal calendar</a>
</div>
<Club:ImageThumbnail ID="thumb1" runat="server" ImageSize="Large" PhotoID='<%# Eval("photo") %>' />
<p>
<asp:Label Text='<%# Eval("description") %>' runat="server" ID="descriptionLabel" />
</p>
<div class="dashedline" ></div>
<asp:Panel ID="pnlAction" runat="server" CssClass="actionbuttons" >
<table border="0" cellpadding="2" cellspacing="2">
<tr>
<td>
<asp:Label runat="server" ID="Label2" Text="Action<br />Required" Width="80px" Font-Bold="true"
ForeColor="#cc0000" Font-Size="14px" />
</td>
<td>
<img src="images/RedArrow.jpg" alt="Red Arrow Right" />
</td>
<td>
<asp:CheckBox runat="server" ID="cbxCert" Height="30px" Text="Check to Confirm Attendance" /><br />
<asp:CustomValidator runat="server" ID="rfvConfirm"
ErrorMessage="You must check the box to continue" Font-Bold="true"
ForeColor="#cc0000" ClientValidationFunction="ensureChecked" /> <br />
<Club:RolloverLink ID="rlnkSignUp" runat="server" Text = "I will be attending this event"
OnClick="rlnkSignUp_OnClick" ToolTip="I hereby certify that I am commiting to attending this event."
/>
</td>
</tr>
</table>
</asp:Panel>
<asp:Panel runat="server" ID="pnlActionCancel" CssClass="actionbuttons" >
<table border="0" cellpadding="2" cellspacing="2">
<tr>
<td>
<asp:Label runat="server" ID="lblDupSignup" Text="You are alredy signed up for this event" ForeColor="#cc0000" Font-Bold="true" Font-Size="14px" />
</td>
<td>
</td>
<td>
<asp:CheckBox runat="server" ID="cbxCancel" Height="30px" Text="Check to Cancel Attendance" /><br />
<asp:CustomValidator runat="server" ID="CustomValidator1"
ErrorMessage="You must check the box to continue" Font-Bold="true"
ForeColor="#cc0000" ClientValidationFunction="ensureChecked" /> <br />
<Club:RolloverLink ID="rlnCancel" runat="server" Text="I'm cancelling my participation"
OnClick="rlnCancel_OnClick" />
</td>
</tr>
</table>
</asp:Panel>
</ItemTemplate>
</asp:FormView>
</asp:Panel>
</div>
I've set the ViewStateMode to "Disabled". I'm just hoping it won't back fire somewhere else.
Your existing code might work if you drop an update panel and place your controls inside it.
Alternatively you can create a property in your page like
private bool myRowCount;
protected bool HasRowsMyData
{
get { return myRowCount; }
set { myRowCount=value; }
}
Then inside your selectedIndex change event
if (dt.Rows.Count == 1)
{
HasRowsMyData=true;
//DataBind your controls here
YourUpdatePanel.Update();
}
Inside your aspx on panels you can set each panel's visible property like this so whenever page is updated they will turn on/off depeding upon the result
Visible='<%#HasRowsMyData%>'
Visible='<%#!HasRowsMyData%>'
If you like to do it client side I advise jQuery's toggle function
jQuey:toggle()

Formview: check if record exist when user try to insert data ASP.NET C#

Is there a way were I could generate a message box if a record exist in the database after the user clicked the insert link button? I want the formview to check if record exist if not make an insert.
Help would be much appreciated.
Thanks in advance :)
Here's a sample of my code:
Manage Books
Add/Remove Books
Note: For the book ID/ISBN please refer to the barcode in the ISBN, usually located
at the back of the book. A barcode reader is required.
<EditItemTemplate>
Book ID/ISBN:
<asp:Label ID="bookidLabel1" runat="server" Text='<%# Eval("bookid") %>' />
<br />
Title:
<asp:TextBox ID="booktitleTextBox" runat="server"
Text='<%# Bind("booktitle") %>' />
<br />
Author's lastname:
<asp:TextBox ID="lastnameTextBox" runat="server"
Text='<%# Bind("lastname") %>' />
<br />
Author's firstname:
<asp:TextBox ID="firstnameTextBox" runat="server"
Text='<%# Bind("firstname") %>' />
<br />
Description:
<asp:TextBox ID="descriptionTextBox" runat="server"
Text='<%# Bind("description") %>' />
<br />
Category:
<asp:TextBox ID="categoryidTextBox" runat="server"
Text='<%# Bind("categoryid") %>' />
<br />
Date added:
<asp:TextBox ID="dateaddedTextBox" runat="server"
Text='<%# Bind("dateadded") %>' />
<br />
Status:
<asp:TextBox ID="statusidTextBox" runat="server"
Text='<%# Bind("statusid") %>' />
<br />
Quantity:
<asp:TextBox ID="quantityTextBox" runat="server"
Text='<%# Bind("quantity") %>' />
<br />
name:
<asp:TextBox ID="nameTextBox" runat="server" Text='<%# Bind("name") %>' />
<br />
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True"
CommandName="Update" Text="Update" />
<asp:LinkButton ID="UpdateCancelButton" runat="server"
CausesValidation="False" CommandName="Cancel" Text="Cancel" />
</EditItemTemplate>
<InsertItemTemplate>
Book ID:
<asp:TextBox ID="bookidTextBox" runat="server" Text='<%# Bind("bookid") %>' />
<asp:RequiredFieldValidator ID="RequesFieldValidator1" runat="server" ErrorMessage="* Required" ControlToValidate="bookidTextBox" ValidationGroup="InsertBook">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator" runat="server" Display="Dynamic" ControlToValidate="bookidTextBox" ValidationExpression="^([\S\s]{13,13})$" ErrorMessage="Invalid ID/ISBN. Please try again" ValidationGroup="InsertBook">
</asp:RegularExpressionValidator>
<br />
Title:
<asp:TextBox ID="booktitleTextBox" runat="server"
Text='<%# Bind("booktitle") %>' />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="* Required" ControlToValidate="booktitleTextBox" ValidationGroup="InsertBook">
</asp:RequiredFieldValidator>
<br />
Author's lastname:
<asp:TextBox ID="lastnameTextBox" runat="server"
Text='<%# Bind("lastname") %>' />
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="* Required" ControlToValidate="lastnameTextBox" ValidationGroup="InsertBook">
</asp:RequiredFieldValidator>
<br />
Author's firstname:
<asp:TextBox ID="firstnameTextBox" runat="server"
Text='<%# Bind("firstname") %>' />
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="* Required" ControlToValidate="firstnameTextBox" ValidationGroup="InsertBook">
</asp:RequiredFieldValidator>
<br />
Description:
<asp:TextBox ID="descriptionTextBox" runat="server"
Text='<%# Bind("description") %>' />
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ErrorMessage="* Required" ControlToValidate="descriptionTextBox" ValidationGroup="InsertBook">
</asp:RequiredFieldValidator>
<br />
Category:
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="categoryDataSource" DataTextField="name"
DataValueField="categoryid" SelectedValue='<%# Bind("categoryid", "{0}") %>'>
</asp:DropDownList>
<asp:SqlDataSource ID="categoryDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:LibrarySystemConnectionString %>"
SelectCommand="SELECT [categoryid], [name] FROM [TblCategory]">
</asp:SqlDataSource>
<br />
Date added:
<asp:TextBox ID="dateaddedTextBox" runat="server"
Text='<%# Bind("dateadded") %>'/>
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ErrorMessage="* Required" ControlToValidate="dateaddedTextBox" ValidationGroup="InsertBook">
</asp:RequiredFieldValidator>
<%--<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="dateaddedTextBox" ErrorMessage="RegularExpressionValidator"
ValidationExpression="(19|20)\d\d(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])">
</asp:RegularExpressionValidator>--%>
<br />
Status:
<asp:DropDownList ID="DropDownList2" runat="server"
DataSourceID="statusDataSource" DataTextField="statusname"
DataValueField="statusid" SelectedValue='<%# Bind("statusid", "{0}") %>'>
</asp:DropDownList>
<asp:SqlDataSource ID="statusDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:LibrarySystemConnectionString %>"
SelectCommand="SELECT [statusid], [statusname] FROM [BookStatus]">
</asp:SqlDataSource>
<br />
Quantity:
<asp:TextBox ID="quantityTextBox" runat="server"
Text='<%# Bind("quantity") %>' />
<asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server" ErrorMessage="* Required" ControlToValidate="quantityTextBox" ValidationGroup="InsertBook">
</asp:RequiredFieldValidator>
<br />
<asp:Button ID="InsertButton" runat="server" CausesValidation="True" CommandName="Insert" Text="Add" ValidationGroup="InsertBook"/>
<asp:Button ID="InsertCancelButton" runat="server"
CausesValidation="False" CommandName="Cancel" Text="Cancel" />
</InsertItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="NewButton" runat="server" CausesValidation="False"
CommandName="New" Text="New" />
</ItemTemplate>
<EmptyDataTemplate>
<asp:LinkButton ID="NewButton" runat="server" CausesValidation="False"
CommandName="New" Text="New" />
</EmptyDataTemplate>
<HeaderTemplate>
Add a new book
</HeaderTemplate>
</asp:FormView>
You can check in the ItemInserting method.
Something like:
void FormViewName_ItemInserting(object sender, FormViewInsertEventArgs e)
{
string somevalue = e.Values["somefieldtoget"];
//make your calls to the DB to check the somevalue doesn't exist
if(exists)
e.Cancel = true;
}
You can also do this on the data sources Inserting Method (sql datasource assumed) as well....
void datasourcename_Inserting(object sender, SqlDataSourceCommandEventArgs e)
{
...
}
Another approach as mentioned by #steve-wellens is if you have a primary key that is based on one or more of the fields in the form view (not an auto generated number then below will work great for catching an attempt to insert a duplicate key/record.
void FormViewName_ItemInserted(object sender, FormViewInsertedEventArgs e)
{
if (e.Exception != null)
{
if (((SqlException)e.Exception).Number == 2627)
{
e.ExceptionHandled = true;
e.KeepInInsertMode = true;
// Display error message.
}
}
}
It would be better to put a unique index on the table and catch exceptions that occur when an attempt is made to insert a duplicate record.
It's the simplest way to ensure integrity. Otherwise you have to start a read transaction to handle the case where between the time you check and the time you insert, some other process is doing the exact same thing.

Categories