asp.net TextBox change Text property - c#

I set my textBox Text property with data loaded from the Database. Later the User enter a new value and click on Save to update this info into the database. My problem is that the textBox.Text never change its value.
My TextBox
<asp:TextBox ID="firstNameModal" runat="server" Width="300px" />
When I load the data:
private void loadMyAccount(int id)
{
var query = (from u in db.Users
where u.Id == id
select u).FirstOrDefault();
// Modal data
firstNameModal.Text = query.FirstName;
}
My save button call the method to update the FirstName value:
protected void saveProfile_Click(object sender, EventArgs e)
{
try
{
int id = (int)HttpContext.Current.Session["userId"];
var query = (from u in db.Users
where u.Id == id
select u).FirstOrDefault();
query.FirstName = firstNameModal.Text;
db.SaveChanges();
} catch(Exception ex)
{
Console.Write(ex.ToString());
}
}
I'm new in webforms, but what am I doing wrong?
Here is my form:
<form id="form1" runat="server">
<uc:Header ID="homeHeader" runat="server" />
<div class="col-xs-12 col-sm-12 col-md-6 col-lg-6 col-xs-offset-0 col-sm-offset-0 col-md-offset-3 col-lg-offset-3 toppad" >
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-title"><asp:Label ID="UserName" runat="server"/></h3>
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-3 col-lg-3 " align="center"> <img alt="User Pic" src="../img/myAccount.png" class="img-circle img-responsive" /> </div>
<div class=" col-md-9 col-lg-9 ">
<table class="table table-user-information">
<tbody>
<tr>
<td>Full Name:</td>
<td><asp:Label ID="fullName" runat="server" /></td>
</tr>
<tr>
<td>Date of Birth</td>
<td><asp:Label ID="dob" runat="server" /></td>
</tr>
<tr>
<td>Gender</td>
<td><asp:Label ID="gender" runat="server" /></td>
</tr>
<tr>
<td>Phone</td>
<td><asp:Label ID="phone" runat="server" /></td>
</tr>
<tr>
<td>Home Address</td>
<td><asp:Label ID="homeAddress" runat="server" /></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="panel-footer">
<asp:Button ID="editProfile" runat="server" CssClass="btn btn-primary" Text="Edit Profile" OnClientClick="$('#editProfileModal').modal(); return false;" />
<asp:Button ID="myBooks" runat="server" CssClass="btn btn-primary" Text="View my books" OnClick="myBooks_Click" />
</div>
</div>
</div>
<!--- Modal Edit Profile --->
<div class="modal fade" id="editProfileModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button aria-hidden="true" data-dismiss="modal" class="close" type="button">X</button>
<h4 class="modal-title"><strong><asp:Label ID="modalFullName" runat="server" /></strong></h4>
</div>
<div class="modal-body">
<div class="alert alert-info fade in">
<asp:Label runat="server" Text="First Name:" Width="90px" />
<asp:TextBox ID="firstNameModal" runat="server" Width="300px" /> <br /> <br />
<asp:Label runat="server" Text="Last Name:" Width="90px" />
<asp:TextBox ID="lastNameModal" runat="server" Width="300px" /> <br /> <br />
<asp:Label runat="server" Text="Date of Birth:" Width="90px" />
<asp:TextBox ID="dobModal" runat="server" Width="300px" /> <br /> <br />
<asp:Label runat="server" Text="Gender:" Width="90px" />
<asp:TextBox ID="genderModal" runat="server" Width="300px" /> <br /> <br />
<asp:Label runat="server" Text="Phone:" Width="90px" />
<asp:TextBox ID="phoneModal" runat="server" Width="300px" /> <br /> <br />
<asp:Label runat="server" Text="Address:" Width="90px" />
<asp:TextBox ID="homeAddressModal" runat="server" Width="300px" /> <br /> <br />
</div>
</div>
<div class="modal-footer">
<asp:Button ID="saveProfile" OnClick="saveProfile_Click" runat="server"
CssClass="btn btn-primary" Text="Save" />
<button data-dismiss="modal" class="btn btn-default" type="button">Close</button>
</div>
</div>
</div>
</div>
</form>
Code behind:
public partial class Views_MyAccount : System.Web.UI.Page
{
LibraryEntities db = new LibraryEntities();
protected void Page_Load(object sender, EventArgs e)
{
if(HttpContext.Current.Session["userId"].Equals(0))
{
Response.Redirect("Login.aspx");
}
else
{
loadMyAccount((int) HttpContext.Current.Session["userId"]);
}
}
private void loadMyAccount(int id)
{
var query = (from u in db.Users
where u.Id == id
select u).FirstOrDefault();
UserName.Text = query.FirstName + " " + query.LastName;
fullName.Text = query.FirstName + query.LastName;
DateTime dt = (DateTime) query.Dob;
dob.Text = dt.ToString("MM/dd/yyyy");
gender.Text = (query.Gender == false ? "Female" : "Male");
phone.Text = query.Phone;
homeAddress.Text = query.Address;
// Modal data
modalFullName.Text = query.FirstName + " " + query.LastName;
firstNameModal.Text = query.FirstName;
lastNameModal.Text = query.LastName;
dobModal.Text = dt.ToString("MM/dd/yyyy");
genderModal.Text = (query.Gender == false ? "Female" : "Male");
phoneModal.Text = query.Phone;
homeAddressModal.Text = query.Address;
}
protected void myBooks_Click(object sender, EventArgs e)
{
}
protected void saveProfile_Click(object sender, EventArgs e)
{
try
{
int id = (int)HttpContext.Current.Session["userId"];
var query = (from u in db.Users
where u.Id == id
select u).FirstOrDefault();
query.FirstName = firstNameModal.Text;
db.SaveChanges();
} catch(Exception ex)
{
Console.Write(ex.ToString());
}
}
}

Double check that the text box and the save profile button are in the same <form runat="server"> HTML tag. Usually this is the case when the page is using a site.master file.
After that, try to check the value of the textbox in the different events of the page life cycle using the debugger.
EDIT:
I think you need to wrap the loadMyAccount method in a IsPostBack conditional, something like this:
protected void Page_Load(object sender, EventArgs e)
{
if(HttpContext.Current.Session["userId"].Equals(0))
{
Response.Redirect("Login.aspx");
}
else
{
if(!IsPostBack)
{
loadMyAccount((int) HttpContext.Current.Session["userId"]);
}
}
}
That will prevent your Page_Load from overwriting the user's input.

Related

How can I select the record in the grid view and delete or edit this record? In Asp.Net Web Form

How can I select the record in the grid view and delete or edit this record? In Asp.Net Web Form
I want this to be done with the Bootstrap modal
I do this with Entity Framework
I have only been able to code to add
The methods I know for editing and deleting are not suitable for this project and they do not work on Bootstrap Modal
Html Code:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="ProductControl.aspx.cs" Inherits="AppData.Pages.ProductControl" %>
<asp:Content ID="HeadContent" ContentPlaceHolderID="Head" runat="server">
<script src="../Scripts/jquery-3.6.0.slim.min.js"></script>
<script src="../Scripts/Site.js"></script>
</asp:Content>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<div class="container">
<div class="row">
<div class="col-md-12 table-responsive" id="ProductDiv">
<div class="d-flex justify-content-between align-items-center mb-3 mt-3">
<h4>List of Products</h4>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel" runat="server">
<ContentTemplate>
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#ModalAdd">
Add Product
</button>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<asp:GridView ID="GridView" runat="server" CssClass="table text-center table-bordered table-hover" HeaderStyle-CssClass="table-dark" AutoGenerateColumns="false" DataKeyNames="Id" OnRowCommand="GridView_RowCommand">
<Columns>
<asp:TemplateField HeaderText="" ItemStyle-Font-Size="Small">
<HeaderTemplate>Row</HeaderTemplate>
<ItemTemplate><%# Container.DataItemIndex+1 %></ItemTemplate>
<ItemStyle Wrap="False" />
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Price" HeaderText="Price" />
<asp:BoundField DataField="Type" HeaderText="Type" />
<asp:BoundField DataField="Barcode" HeaderText="Barcode" />
<asp:TemplateField HeaderText="Commands" ItemStyle-Font-Size="Small">
<ItemTemplate>
<asp:LinkButton CssClass="btn btn-warning" ID="BtnEdit" runat="server">Edit</asp:LinkButton>
<asp:LinkButton CssClass="btn btn-danger" ID="BtnDelete" runat="server" data-toggle="modal" data-target="#ModalDelete">Delete</asp:LinkButton>
<asp:LinkButton CssClass="btn btn-info" ID="BtnDetail" runat="server">Detail</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div class="row">
<asp:Label ID="LblNotFound" runat="server" Text="No Product Found" CssClass="col-12 alert alert-danger text-center" Visible="false"></asp:Label>
</div>
</div>
<!-- Modal Add -->
<asp:UpdatePanel ID="UpdatePanelModalAdd" runat="server">
<ContentTemplate>
<div class="modal" id="ModalAdd">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add New Record</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-6">
<p>Name:</p>
<asp:TextBox ID="Name" placeholder="Name" runat="server" CssClass="form-control"></asp:TextBox>
</div>
<div class="col-6">
<p>Price:</p>
<asp:TextBox ID="Price" placeholder="Price" runat="server" CssClass="form-control"></asp:TextBox>
</div>
</div>
<div class="row">
<div class="col-6">
<br />
<p>Type:</p>
<asp:TextBox ID="Type" placeholder="Type" runat="server" CssClass="form-control"></asp:TextBox>
</div>
<div class="col-6">
<br />
<p>Barcode:</p>
<asp:TextBox ID="Barcode" placeholder="Barcode" runat="server" CssClass="form-control"></asp:TextBox>
</div>
</div>
</div>
<div class="modal-footer">
<asp:Button ID="BtnCreate" runat="server" CssClass="btn btn-success" Text="Create" OnClick="BtnCreate_Click" />
<asp:Button ID="BtnCancel" runat="server" CssClass="btn btn-danger" Text="Cancel" data-dismiss="modal" />
</div>
</div>
</div>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="BtnCreate" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="BtnCancel" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<!-- Modal Detail -->
<asp:UpdatePanel ID="UpdatePanelModalDetail" runat="server">
<ContentTemplate>
<div class="modal" id="ModalDetail">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Detail Record</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-6">
<p>Name:</p>
<asp:Label ID="LblName" CssClass="text-secondary" runat="server" Text=""></asp:Label>
</div>
<div class="col-6">
<p>Price:</p>
<asp:Label ID="LblPrice" CssClass="text-secondary" runat="server" Text=""></asp:Label>
</div>
</div>
<div class="row">
<div class="col-6">
<br />
<p>Type:</p>
<asp:Label ID="LblType" CssClass="text-secondary" runat="server" Text=""></asp:Label>
</div>
<div class="col-6">
<br />
<p>Barcode:</p>
<asp:Label ID="LblBarcode" CssClass="text-secondary" runat="server" Text=""></asp:Label>
</div>
</div>
</div>
<div class="modal-footer">
<asp:Button ID="Button1" runat="server" CssClass="btn btn-success" Text="Create" OnClick="BtnCreate_Click" />
<asp:Button ID="Button2" runat="server" CssClass="btn btn-danger" Text="Cancel" data-dismiss="modal" />
</div>
</div>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<!-- Modal Delete -->
<asp:UpdatePanel ID="UpdatePanelModalDelete" runat="server">
<ContentTemplate>
<div class="modal" id="ModalDelete">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Delete Record</h4>
</div>
<div class="modal-body">
<h6 class="text-center">Are you sure you want to delete this record?</h6>
<br />
<div class="text-center">
<asp:Button ID="Delete" CssClass="btn btn-danger border-2 border-dark" runat="server" Text="Delete" CommandArgument='<%# Eval("Id") %>' CommandName="Delete" />
<button id="Cancel" class="btn btn-light border-2 border-dark" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Delete" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</div>
</asp:Content>
And Backend Code:
using AppData.Models;
using System;
using System.Collections.Generic;
using System.EnterpriseServices;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AppData.Pages
{
public partial class ProductControl : System.Web.UI.Page
{
Models.ProductDbEntities Db = new Models.ProductDbEntities();
protected void Page_Load(object sender, EventArgs e)
{
if (GridView.Rows.Count > 0)
{
LblNotFound.Visible = false;
}
else
{
GridView.DataSource = Db.TblProducts.ToList();
GridView.DataBind();
}
}
protected void BtnCreate_Click(object sender, EventArgs e)
{
TblProduct Row = new TblProduct();
Row.Name = Name.Text;
Row.Price = Price.Text;
Row.Type = Type.Text;
Row.Barcode = Convert.ToInt64(Barcode.Text);
Db.TblProducts.Add(Row);
Db.SaveChanges();
Response.Redirect("ProductControl.aspx");
}
protected void BtnCancel_Click(object sender, EventArgs e)
{
Response.Redirect("Pages/ProductControl.aspx");
}
protected void GridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
var id = e.CommandArgument;
if (e.CommandName == "Delete")
{
Int64 Id = Convert.ToInt64(id);
var Row = Db.TblProducts.FirstOrDefault(n => n.Id == Id);
Db.TblProducts.Remove(Row);
Db.SaveChanges();
Response.Redirect("DataControl.aspx");
GridView.DataSource = Db.TblProducts.ToList();
GridView.DataBind();
}
}
}
}
I understand your approach, but if you are using bootstrap modals you need to write a little bit more code.
One way to achieve this is by following the next steps:
In the Delete modal add a hidden field to hold the selected productId and an event handler for the delete button:
<div class="modal-body">
<h6 class="text-center">Are you sure you want to delete this record?</h6>
<br />
<!--add this inside delete modal -->
<input type="hidden" id="productIdToDelete" runat="server" />
<div class="text-center">
<!-- remove CommandArgument and CommandName from the Delete button. They are useless in the popup. -->
<!-- add an event handler to OnClick-->
<asp:Button ID="Delete" CssClass="btn btn-danger border-2 border-dark" runat="server" Text="Delete" OnClick="BtnDelete_Click" />
...
Create event handlers for when the modal is opened in order to propagate the productId from the current row in the grid to the modal:
<script src="../Scripts/Site.js"></script>
<script type="text/javascript">
$(document).ready(
function () {
//use a jquery selector to assign an event handler to all Delete Buttons found on the page (nottice they all start with the same prexif)
$("[id*=MainContent_GridView_BtnDelete]").click(function () {
//get the id of the product from the selected row first cell and assign it to the hidden field in the modal
$("#MainContent_productIdToDelete").val($(this).closest('tr').find('td').eq(0).html());
});
});
</script>
Finally, handle the delete event in the code behind:
protected void BtnDelete_Click(object sender, EventArgs e)
{
string idVal = Request.Form[productIdToDelete.UniqueID];
var id = Convert.ToInt64(idVal);
// implement delete logic ...
}
Use the same approach for Edit. (Look at this example.)

ASP.NET FormView OnItemUpdate - not updated new values

I have problem with event OnItemUpdate.. in dictionary NewValues are old values. What is wrong? How to get new values?
<asp:FormView
runat="server"
ID="frvKartaCharakterystyk"
RenderOuterTable="false"
DefaultMode="Edit"
OnItemUpdating="frvKartaCharakterystyk_ItemUpdating">
<EditItemTemplate>
<div class="form-horizontal">
<div class="form-group">
<label class="col-sm-3 control-label" for="inputProdukt">Produkt</label>
<div class="col-sm-9">
<asp:TextBox runat="server" id="inputProdukt" CssClass="form-control" Text='<%# Bind("Produkt") %>' />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-6 col-sm-3"><asp:LinkButton runat="server" CommandName="Update" type="button" class="btn btn-primary btn-lg btn-block">Zapisz</asp:LinkButton></div>
<div class="col-sm-3"><asp:LinkButton runat="server" CommandName="Cancel" OnClick="Cancel_Click" type="button" class="btn btn-default btn-lg btn-block">Anuluj</asp:LinkButton></div>
</div>
</div>
</EditItemTemplate>
</asp:FormView>
My CodeBehind:
protected void frvKartaCharakterystyk_ItemUpdating(object sender, FormViewUpdateEventArgs e)
{
try
{
this.KartaCharakterystyk.Produkt = (string)e.NewValues["Produkt"];
Response.Redirect("KartyCharakterystyk.aspx#record-" + (KartaCharakterystyk.Id - 1));
}
catch (Exception ex)
{
}
}
The problem was in Page_Load:
this.frvKartaCharakterystyk.DataSource = new object[] { this.KartaCharakterystyk };
this.frvKartaCharakterystyk.DataBind();
Changed to:
if (!IsPostBack)
{
this.frvKartaCharakterystyk.DataSource = new object[] { this.KartaCharakterystyk };
this.frvKartaCharakterystyk.DataBind();
}

Button or link button event does not fire time to time

In my whole project I have several events and surprising thing is that sometime some event fire up and sometime doesnot.I don't know hat is going on. I have tried many option after seraching from google. Please someone help me. I am in very bad situation.
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
if (Session["userid"] != null)
{
if (FileUpload1.HasFile)
{
string str = FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(Server.MapPath(".")
+ "//images//" + str);
string path = "~//images//" + str.ToString();
con.Open();
Label1.Text = "File uploaded successfully";
main addinfo = new main();
string Id = Request.QueryString["id"];
string SQL = "insert into
mandir(with_user,name,place,with_district,with_religion,
with_religion_category,description,photo)
values('" + Session["userid"] + "','" + txttemplename.Text.Trim()
+ "','" + txtaddress.Text.Trim() + "','" +
ddldistrict.SelectedItem.Value + "','" +
ddlreligion.SelectedItem.Value + "','" +
ddlreligioncategory.SelectedItem.Value +
"','" + txtdescription.Value + "','" + path + "')";
addinfo.saveData(SQL);
con.Close();
txttemplename.Text = "";
txtaddress.Text = "";
txtdescription.Value = "";
string message1 = "Thank you for providing the information";
Page.ClientScript.RegisterStartupScript(this.GetType(),
"Popup", "ShowPopup('" + message1 + "');", true);
// lblenquirymsg.Text = "";
}
else
{
Label1.Text = "File not uploaded successfully";
}
}
else
{
// lblinfo.Text = "You Must Login Or Register To give information";
string message = "You Must Login Or Register To Comment";
Page.ClientScript.RegisterStartupScript(this.GetType(),
"Popup", "ShowPopup('" + message + "');", true);
}
}
catch (Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}
<div class="weltext">
<h2>Add information</h2>
<div>
<div class="txt-st4" style="margin-bottom:8px; margin-top:10px;">Please fill the form below to provide information.</div>
<div style="padding:0px 0 10px 0;">
<form method="post">
<div style="margin-bottom:3px;"></div>
<div style="margin-bottom:7px;">
<div style="margin-bottom:3px;">Temple Name <span style="color:#F00">*<br />
</span><asp:TextBox ID="txttemplename" class="input_field1 verifyText" runat="server" style="margin-left: 0px" ></asp:TextBox>
</div>
<%-- <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ErrorMessage="please input alphabets." ControlToValidate="txtfullname"
ValidationExpression="^[a-zA-Z]+$" Height="19px" Width="165px"></asp:RegularExpressionValidator>--%>
<asp:RequiredFieldValidator ID="rfvtemplelname" runat="server"
ControlToValidate="txttemplename" ErrorMessage="*"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revtemplelname" runat="server"
ControlToValidate="txttemplename" ErrorMessage="Only alphabets are allowed"
ForeColor="Red" ValidationExpression="^[a-zA-Z ]+$" > </asp:RegularExpressionValidator>
</div>
<div style="margin-bottom:4px;">
<div class="field required">
<div style="margin-bottom:3px;">
Address<span style="color:#F00">*<br /></span>
<asp:TextBox ID="txtaddress" class="input_field1 verifyText" runat="server" style="margin-left: 0px" ></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvaddress" runat="server"
ControlToValidate="txtaddress" ErrorMessage="Please enter valid address"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revaddress" runat="server"
ControlToValidate="txtaddress" ErrorMessage="Only alphabets are allowed"
ForeColor="Red" ValidationExpression="^[a-zA-Z ]+$" > </asp:RegularExpressionValidator>
</div>
</div>
</div>
<div style="margin-bottom:4px;">
<div class="field required">
<div style="margin-bottom:3px;"> Choose district <span style="color:#F00">*<br />
</span><asp:DropDownList ID="ddldistrict" runat="server" class="input_field1 verifyText" OnLoad="ddldistrict_Load" style="margin-left: 0px"></asp:DropDownList></div><div style="margin-bottom:4px;">
<div class="field required">
<br />
</div></div>
<div style="margin-bottom:3px;"> Choose religion<span style="color:#F00">*<br />
</span><asp:DropDownList ID="ddlreligion" class="input_field1 verifyText" runat="server" OnLoad="ddlreligion_Load" style="margin-left: 0px"></asp:DropDownList></div><div style="margin-bottom:4px;">
<div class="field required">
<br />
</div></div>
<div style="margin-bottom:3px;"> Choose religion category <span style="color:#F00">*<br />
</span><asp:DropDownList ID="ddlreligioncategory" class="input_field1 verifyText" runat="server" OnLoad="ddlreligioncategory_Load" style="margin-left: 0px" ></asp:DropDownList>
</div><div style="margin-bottom:4px;">
<div class="field required">
<br />
</div></div>
<%--<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server"
ErrorMessage="please input alphabets." ControlToValidate="txtaddress"
ValidationExpression="^[a-zA-Z]+$" Height="19px" Width="165px"></asp:RegularExpressionValidator>--%>
</div>
</div>
<div style="margin-bottom:3px;">Description<span style="color:#F00">*</span></div>
<div style="margin-bottom:4px;">
<div class="field required">
<textarea id="txtdescription" runat="server" name="description" class="text_area" style="width: 532px; height: 180px"></textarea>
<%-- <asp:RequiredFieldValidator ID="rfvdescription" runat="server" ControlToValidate="txtdescription"
ErrorMessage="*" InitialValue="Select"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revdescription" Runat="server"
ErrorMessage="ERROR: Please enter a valid description<br/>" SetFocusOnError="true" Display="Dynamic"
ControlToValidate="txtdescription" ValidationGroup="MandatoryContent"
ValidationExpression="^[A-Za-z'\-\p{L}\p{Zs}\p{Lu}\p{Ll}\']+$"
ForeColor="Red"></asp:RegularExpressionValidator>--%>
</div>
</div>
Choose picture:<br />
<asp:FileUpload ID="FileUpload1" runat="server" style="margin-left: 0px" /><br />
<%-- <asp:Button ID="Button1" runat="server" Text="Upload Image" onclick="Button1_Click" /><br >--%>
<br />
<span style="color:#F00">
<asp:Label ID="Label1" runat="server" Text="Label" Visible="False"></asp:Label>
<span style="color:#F00">
<div id="dialog" style="display: none">
</div>
<asp:Button id="btnSubmit" Text="Submit " runat="server" class="btn" OnClick="btnSubmit_Click" />
<%--<asp:Button ID="btnSubmit" Text="Submit" runat="server" value="Submit Now" class="btn" CausesValidation="False" style="margin-left: 13px" OnClick="btnSubmit_Click" />--%>
<br />
</span>
</span>
<br />
<div>
<%-- <asp:Button ID="btnReset" Text="Reset Form" runat="server" value="Reset Form" class="btn" OnClick="btnReset_Click" />--%>
<asp:Label ID="lblenquirymsg" runat="server"></asp:Label>
</div>
</form>
</div>
</div>
<p>
<asp:Label ID="lblenquirymsg1" runat="server"></asp:Label>
</p>
The above event is also not firing.

CustomValidator Error Message not showing up in ValidationSummary

I'm kind of baffled. Can someone help me point out why my validation summary is not showing the custom validators? When I step through the code in the custom validators the args.IsValid is set to false.
<asp:ValidationSummary ID="ValidationSummary1" runat="server" CssClass="alert alert-danger" DisplayMode="List" ShowSummary="true" ValidationGroup="ValidateUser" />
<fieldset class="form-horizontal">
<legend><asp:Literal runat="server" ID="litFirstName" /> <asp:Literal runat="server" ID="litLastName" /><asp:Literal runat="server" id="litLockedBadge" /></legend> <div class="control-group">
<label class="control-label" for="inputEmail">
<asp:CustomValidator ID="cvEmailAddress" runat="server" ValidationGroup="ValidateUser" Text="*" CssClass="required" ControlToValidate="txtEmailAddress" Display="Dynamic" OnServerValidate="cvValidateEmail" />
<asp:RequiredFieldValidator runat="server" CssClass="required" Display="Dynamic" ControlToValidate="txtEmailAddress" Text="*" ErrorMessage="Email Address Required" ValidationGroup="ValidateUser" /> Email Address</label>
<div class="controls">
<asp:Textbox Text="test" runat="server" id="txtEmailAddress" ClientIDMode="Static" CssClass="span3" />
</div>
</div>
<div class="control-group input-append">
<label class="control-label" for="txtUserName"><asp:CustomValidator runat="server" ID="cvUserName" Text="*" CssClass="required" Display="Dynamic" OnServerValidate="cvValidateUserName" ValidationGroup="ValidateUser" /><asp:RequiredFieldValidator runat="server" Display="Dynamic" CssClass="required" ControlToValidate="txtUserName" Text="*" ErrorMessage="Username Required" ValidationGroup="ValidateUser" /> Username</label>
<div class="controls">
<asp:Textbox Text="test" runat="server" id="txtUserName" ClientIDMode="Static" CssClass="span3" />
<asp:LinkButton data-attr="email" ID="lnkEmailUsername" runat="server" CssClass="btn" OnClick="btn_ClickEmailUsername" ClientIDMode="Static"><i class="icon-envelope"></i></asp:LinkButton>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputEmail"></label>
<div class="controls">
<div class="btn-group">
<asp:Button runat="server" ID="btnUnlockAccount" CssClass="btn" Text="Unlock Account" />
<asp:Button runat="server" ID="btnResetPassword" CssClass="btn" Text="Reset Password" />
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputEmail"></label>
<div class="controls">
<asp:Button runat="server" ID="btnSubmit" CssClass="btn btn-primary" Text="Update User Account" OnClick="btn_UpdateUserAccount" ValidationGroup="ValidateUser" />
</div>
</div>
</fieldset>
Here is the code behind
//Validate the Username
protected void cvValidateUserName(object source, ServerValidateEventArgs args)
{
string userName = txtUserName.Text;
cvUserName.ErrorMessage = "";
args.IsValid = true;
if (userName.Contains(" "))
{
cvUserName.ErrorMessage = "Username cannot contain spaces. ";
cvUserName.IsValid = false;
}
if (userName.Length > 100 || userName.Length < 8)
{
cvUserName.ErrorMessage += "Username must be between 8 and 100 characters. ";
cvUserName.IsValid = false;
return;
}
}
//Validate Email Address
protected void cvValidateEmail(object source, ServerValidateEventArgs args)
{
var emailAddress = txtEmailAddress.Text;
try
{
new MailAddress(emailAddress);
}
catch (Exception)
{
args.IsValid = false;
return;
}
}
In order for the Validator's error message to display in the ValidationSummary, you need to set the Validators Display="none". I also set Text="".

Add Form in a Modal

I making an add form in my modal. The modal contains 2 dropdownlists, 4 textboxes (1 hidden) and a button for adding.
I bind my dropdown list for the item category then bind my other dropdown list for the item name. However when I change my Item Category in my dropdown list the dropdown list for my item name is not responding or it not binding. Can anyone help me?
<div id="addModal" class="modal fade">
<div class="modal-dialog modal-md">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Add Item</h4>
</div>
<div class="modal-body">
<div class="form-inline form-group">
<asp:Label ID="Label1" CssClass="control-label col-xs-3" runat="server" Text="Category:"></asp:Label>
<div class="col-xs-offset-3">
<asp:DropDownList ID="drpCategory" runat="server" CssClass="form-control col-xs-5" OnTextChanged="drpCategory_TextChanged" />
</div>
</div>
<div class="form-inline form-group">
<asp:Label ID="Label2" CssClass="control-label col-xs-3" runat="server" Text="Item Name:"></asp:Label>
<div class="col-xs-offset-3">
<asp:TextBox ID="txtitem" runat="server" CssClass="form-control col-xs-5" Visible="false" />
<asp:DropDownList ID="drpItem" runat="server" CssClass="form-control col-xs-5" Visible="true" />
</div>
</div>
<div class="form-inline form-group">
<asp:Label ID="Label3" CssClass="control-label col-xs-3" runat="server" Text="Unit:"></asp:Label>
<div class="col-xs-offset-3">
<asp:TextBox ID="txtUnit" runat="server" CssClass="form-control col-xs-5" Enabled="false" />
</div>
</div>
<div class="form-inline form-group">
<asp:Label ID="Label4" CssClass="control-label col-xs-3" runat="server" Text="Quantity:"></asp:Label>
<div class="col-xs-offset-3">
<asp:TextBox ID="txtQty" runat="server" CssClass="form-control col-xs-3" type="number" min="1" onkeypress="return isNumberKey(event)" />
</div>
</div>
</div>
</div>
<div class="modal-footer">
<asp:Button runat="server" ID="btnADD" CssClass="btn btn-sm" OnClick="btnADD_Click" Text="Add" />
</div>
</div>
</div>
then this is the code behind:
public void drpCategory_TextChanged(object sender, EventArgs e)
{
if (drpCategory.Text == "Others")
{
drpItem.Visible = false;
txtitem.Visible = true;
}
else
{
byCateg();
DataBind();
drpItem.Visible = true;
txtitem.Visible = false;
}
}
Is there a problem in my code?

Categories

Resources