Selected Index Changed event not firing both Autopostback property - c#

In my Dropdownlist Selected index change event not firing.Here i use auto post back true &
View state also true.But Selected Index Changed Event not firing
My Code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="AdminEagleViewLogin.aspx.cs" Inherits="AdminEagleViewLogin" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<style>
body{padding-top:20px;}
</style>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div class="container">
<div class="row">
User : <asp:DropDownList ID="drpusr" runat="server" Visible="true" OnSelectedIndexChanged="drpusr_SelectedIndexChanged" AutoPostBack="true" EnableViewState="true" ></asp:DropDownList>
Password: <asp:Label ID="lbluserpw" runat="server"></asp:Label>
<div class="col-md-4 col-md-offset-4">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Please sign in</h3>
</div>
<div class="panel-body">
<form accept-charset="UTF-8" role="form">
<fieldset>
<div class="form-group">
<asp:TextBox ID="txtusr" runat="server"></asp:TextBox>
</div>
<div class="form-group">
<asp:TextBox ID="txtpw" runat="server" TextMode="Password"></asp:TextBox>
</div>
<div class="checkbox">
<label>
<input name="remember" type="checkbox" value="Remember Me"> Remember Me
</label>
</div>
<asp:CheckBox ID="chkremember" runat="server" Visible="false" class="remchkbox" />
<asp:Button ID="submit" runat="server" class="btn btn-lg btn-success btn-block" Text="Submit" OnClick="submit_Click" />
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
</form>
</body>
</html>
ServerSide
User bind to Dropdown is working.
public partial class AdminEagleViewLogin : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
BindUsers();
//lbluserpw.Text = Membership.Provider.GetPassword(drpusr.SelectedValue, String.Empty);
}
protected void submit_Click(object sender, EventArgs e)
{
if (Membership.ValidateUser(txtusr.Text, txtpw.Text))
{
FormsAuthentication.SetAuthCookie(txtusr.Text, chkremember.Checked);
string[] CurrentUserRole = Roles.GetRolesForUser(txtusr.Text);
var admin = "Administrator";
var manager = "Manager";
var user = "User";
if (CurrentUserRole.Contains(admin))
{
Response.Redirect("Administrator.aspx");
}
else if (CurrentUserRole.Contains(manager))
{
Response.Redirect("Manager.aspx");
}
else
{
Response.Redirect("UserPage.aspx");
}
}
else
{
Response.Redirect("AdminEagleViewLogin.aspx");
}
}
protected void BindUsers()
{
DataAccess da = new DataAccess();
drpusr.DataSource = da.GetUsers();
drpusr.DataTextField = "UserName";
drpusr.DataValueField = "UserId";
drpusr.DataBind();
drpusr.Items.Insert(0, new ListItem("-- Select User --", "0"));
drpusr.Items.RemoveAt(1);
}
protected void drpusr_SelectedIndexChanged(object sender, EventArgs e)
{
lbluserpw.Text = Membership.Provider.GetPassword(drpusr.SelectedValue, String.Empty);
}
}

Try this:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindUsers();
}
}

You shouldn't put a form element inside another form:
<form accept-charset="UTF-8" role="form">
<fieldset>
...
<asp:Button ID="submit" runat="server" class="btn btn-lg btn-success btn-block" Text="Submit" OnClick="submit_Click" />
</fieldset>
</form>
remove the inner form.
[Update]
Another problem is the "ID" property of the button.
change it to something else, other than "submit".

Related

How can I get the lblmessage to display only if Confirm button is clicked before Calculate button?

<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Confirm.aspx.cs" Inherits="XEx04Quotation.Confirm" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Confirm quotation</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="Scripts/jquery-1.9.1.min.js"></script>
<script src="Scripts/bootstrap.min.js"></script>
<link href="Content/bootstrap.min.css" rel="stylesheet" />
<link href="Content/site.css" rel="stylesheet" />
</head>
<body>
<form id="form1" runat="server" class="form-horizontal">
<main class="container">
<h1 class="jumbotron">Quotation confirmation</h1>
<div class="form-group">
<label class="col-sm-3 control-label">Sales price</label>
<asp:Label ID="lblSalesPrice" runat="server" CssClass="col-sm-3 bold"></asp:Label>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Discount amount</label>
<asp:Label ID="lblDiscountAmount" runat="server" CssClass="col-sm-3 bold"></asp:Label>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Total price</label>
<asp:Label ID="lblTotalPrice" runat="server" CssClass="col-sm-3 bold"></asp:Label>
</div>
<div class="row">
<h3 class="col-sm-offset-2 col-sm-10">Send confirmation to</h3>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Name</label>
<div class="col-sm-3">
<asp:TextBox ID="txtName" runat="server" CssClass="form-control"></asp:TextBox>
</div>
<div class="col-sm-6">
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtName"
Display="Dynamic" ErrorMessage="Required" CssClass="text-danger"></asp:RequiredFieldValidator>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Email address</label>
<div class="col-sm-3">
<asp:TextBox ID="txtEmail" runat="server" CssClass="form-control"></asp:TextBox>
</div>
<div class="col-sm-6">
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtEmail"
Display="Dynamic" ErrorMessage="Required" CssClass="text-danger"></asp:RequiredFieldValidator>
</div>
</div>
<%-- Quotation and Return buttons --%>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-9">
<%-- buttons go here --%>
<asp:Button ID="Button1" runat="server" Text="Send Quotation" CssClass="btn btn-primary"/>
<asp:Button ID="Button2" runat="server" Text="Return" CssClass="btn btn-primary" PostBackUrl="~/Default.aspx" CausesValidation="false"/>
</div>
</div>
<%-- message label --%>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-11">
<%-- message label goes here --%>
<asp:Label ID="lblmessage" runat="server" Text="Click the Send Quotation button to send the quotation via email" CssClass="text-info"></asp:Label>
</div>
</div>
</main>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace XEx04Quotation
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
UnobtrusiveValidationMode = UnobtrusiveValidationMode.None;
}
protected void btnCalculate_Click(object sender, EventArgs e)
{
if (IsValid)
{
decimal salesPrice = Convert.ToDecimal(txtSalesPrice.Text);
// save the salesPrice into a session state variable
Session["SalesPrice"] = salesPrice;
decimal discountPercent = Convert.ToDecimal(txtDiscountPercent.Text) / 100;
decimal discountAmount = salesPrice * discountPercent;
// save the discountAmount into a session state variable
Session["Discount"] = discountAmount;
decimal totalPrice = salesPrice - discountAmount;
// save the totalPrice into a session state variable
Session["TotalPrice"] = totalPrice;
lblDiscountAmount.Text = discountAmount.ToString("c");
lblTotalPrice.Text = totalPrice.ToString("c");
}
}
protected void Button1_Confirm(object sender, EventArgs e)
{
if(Session["SalesPrice"] != null)
{
Response.Redirect("Confirm.aspx");
}
else
{
// This is the part I am concerned about
lblmessage2.Text = "Click the Calculate button before you click confirm";
}
}
}
}
Hello Everyone,
I am building multi-web application pages using the Default.aspx, Default.aspx.cs and Confirm.aspx and Confirm.aspx.cs. The problem that I am having is that when I click "Confirm" before clicking "Calculate," the event handler displays the "Click the Calculate button before the confirm" at the bottom of the page. It does that even if the Calculate button is clicked before the Confirm and also displays again when I reload the page. How can I get this to only display if the session state value of SalesPrice is null? Otherwise, it will redirect to the confirm page. Here is Default.aspx.cs and other file:
You can do one thing. If you want to get the total calculation first, then disable the confirm button and clicking on the calculate button will enable the button as follows:
<asp:Button ID="Button1" runat="server" Enabled="false" />
protected void btnCalculate_Click(object sender, EventArgs e)
{
Button1.Enabled = True;
if(Session["TotalPrice"] != null)
{
lblMsg.Text = "Please click here to see total calculation";
}
}
protected void Button1_Confirm(object sender, EventArgs e)
{
if(Session["SalesPrice"] != null)
{
Response.Redirect("Confirm.aspx");
}
}
Note: Please follow the naming convention for the event names. Button1 To btnConfirm.
Update 1 - Try the below tested code:
<asp:Button ID="btnCalculate" runat="server" Text="Calculate" OnClick="btnCalculate_Click" />
<asp:Button ID="btnConfirm" runat="server" Text="Confirm" OnClick="btnConfirm_Click" />
<asp:Label ID="lblMsg" runat="server"></asp:Label>
private int buttonWasClicked = 0; //Kept a variable type of int and with a default value 0
protected void btnCalculate_Click(object sender, EventArgs e)
{
buttonWasClicked = 1; //If clicked, then 1
Session["value"] = Convert.ToInt32(buttonWasClicked); //Then kept in session
lblMsg.Text = "Total Price - 10,000";
}
protected void btnConfirm_Click(object sender, EventArgs e)
{
if (Session["value"] != null) //If session not null, then redirect page
{
Response.Redirect("CustomerDetails.aspx");
Session["value"] = null; //Clears the session
}
else
{
lblMsg.Text = "Click the calculate button first";
}
}

Trying to enable show/hide feature in asp.net

I am trying to enable show/hide password feature. I am creating an asp.net web form using C#.
My code is as below,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class show : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox1.Checked == false)
{
TextBox1.TextMode = TextBoxMode.Password;
}
if (CheckBox1.Checked == true)
{
TextBox1.TextMode = TextBoxMode.SingleLine;
}
}
}
On mypage.aspx,
there is a checkbox whose autopostback property is true and a textbox whose textmode is password.
The expected result is:-
show password into text when checkbox is checked.
hide password when checkbox is unchecked.
The problem is :-
This code is working only once i.e. it is not being executed when checkbox is checked or unchecked again.
The textbox becomes blank.
Please help me soon.
You are losing value within TextBox because on selection change, the page loads again, you need to check whether its a postBack or first time load and set the textBox value.
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
string Password = TextBox1.Text;
TextBox1.Attributes.Add("value", Password);
}
}
Your problem will be solved. I've tested it.
Hope it helps!
There's exactly zero need to use a postback for this. An example using jQuery:
Markup:
<label>Password fields are just a UI convenience:</label>
<input type="password" id="password" value="super secret password" />
<label>
<input type="checkbox" id="toggle-password" /> Toggle
</label>
jQuery code:
$(function() {
$('#toggle-password').on('change', function(e) {
var _this = $(this);
if (_this.is(':checked')) {
$('#password').attr({
'type': 'text'
});
} else {
$('#password').attr({
'type': 'password'
});
}
})
});
A vanilla JS version:
var toggle = document.getElementById('toggle-password');
var textbox = document.getElementById('password');
toggle.addEventListener("click", function() {
var isChecked = toggle.checked;
if (isChecked) {
textbox.type = "text";
} else {
textbox.type = "password";
}
})
You can't set the text property of a Password Type field for security reasons.So another way to set the value after changing mode is
if (CheckBox1.Checked == false)
{
string pass = TextBox1.Text;
TextBox1.TextMode = TextBoxMode.Password;
TextBox1.Attributes.Add("value", pass);
}
if (CheckBox1.Checked)
{
TextBox1.TextMode = TextBoxMode.SingleLine;
}
<head runat="server">
<title>Show Hide Password</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#show_password').hover(function show() {
//Change the attribute to text
$('#txtCurrentpassword').attr('type', 'text');
$('.icon').removeClass('fa fa-eye-slash').addClass('fa fa-eye');
},
function () {
//Change the attribute back to password
$('#txtCurrentpassword').attr('type', 'password');
$('.icon').removeClass('fa fa-eye').addClass('fa fa-eye-slash');
});
//CheckBox Show Password
$('#ShowPassword').click(function () {
$('#Password').attr('type', $(this).is(':checked') ? 'text' : 'password');
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$('#show_password1').hover(function show() {
//Change the attribute to text
$('#txtNewPassword').attr('type', 'text');
$('.icon').removeClass('fa fa-eye-slash').addClass('fa fa-eye');
},
function () {
//Change the attribute back to password
$('#txtNewPassword').attr('type', 'password');
$('.icon').removeClass('fa fa-eye').addClass('fa fa-eye-slash');
});
//CheckBox Show Password
$('#ShowPassword').click(function () {
$('#Password').attr('type', $(this).is(':checked') ? 'text' : 'password');
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$('#show_password2').hover(function show() {
//Change the attribute to text
$('#txtConfirmPassword').attr('type', 'text');
$('.icon').removeClass('fa fa-eye-slash').addClass('fa fa-eye');
},
function () {
//Change the attribute back to password
$('#txtConfirmPassword').attr('type', 'password');
$('.icon').removeClass('fa fa-eye').addClass('fa fa-eye-slash');
});
//CheckBox Show Password
$('#ShowPassword').click(function () {
$('#Password').attr('type', $(this).is(':checked') ? 'text' : 'password');
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="container">
<br />
<br />
<br />
<div class="col-md-10">
<div class="" style="display: none" runat="server" id="divStatusMsg">
<asp:HiddenField ID="lblLoginUserId" runat="server" />
<asp:HiddenField ID="HidEncrptedPWD" runat="server" />
<asp:HiddenField ID="HidCurrEncrptedPWD" runat="server" />
<asp:HiddenField ID="hidError" runat="server" />
</div>
</div>
<h2>Update Password</h2>
<label class="col-form-label" style="color: red">(Min 10 Character including 1 Upper, 1 Lower Charcter, 1 Numeric & 1 Special Character)</label>
<div class="row">
<div class="col-md-6">
<label>User Name</label>
<div class="input-group">
<asp:TextBox ID="txtUserName" TextMode="SingleLine" runat="server" CssClass="form-control" Enabled="false"></asp:TextBox>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<label>Current Password</label>
<div class="input-group">
<asp:TextBox ID="txtCurrentpassword" TextMode="Password" runat="server" CssClass="form-control"></asp:TextBox>
<div class="input-group-append">
<button id="show_password" class="btn btn-primary" type="button">
<span class="fa fa-eye-slash icon"></span>
</button>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<label>New Password</label>
<div class="input-group">
<asp:TextBox ID="txtNewPassword" TextMode="Password" runat="server" CssClass="form-control"></asp:TextBox>
<div class="input-group-append">
<button id="show_password1" class="btn btn-primary" type="button">
<span class="fa fa-eye-slash icon"></span>
</button>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<label>Re-Enter Password :</label>
<div class="input-group">
<asp:TextBox ID="txtConfirmPassword" TextMode="Password" runat="server" CssClass="form-control"></asp:TextBox>
<div class="input-group-append">
<button id="show_password2" class="btn btn-primary" type="button">
<span class="fa fa-eye-slash icon"></span>
</button>
</div>
</div>
</div>
</div>
<br />
<!--Button Region-->
<div class="row">
<div class="col-lg-6 text-right" id="divDateSearch">
<div class="form-group">
<button type="button" id="btnSave" runat="server" class="btn btn-success btn-border btn-sm" onserverclick="btnSave_click">Change</button>
<button type="button" id="btnReset" runat="server" class="btn btn-default btn-border btn-sm" onserverclick="btnReset_click">Reset</button>
</div>
</div>
</div>
<!--Button Region-->
</div>
</form>
</body>

Button click doesn't call function

in aspx file when i change the postion of button its work well but when i put it in current psitiion the click method doesnot call;
the function of click is correct
button4(end of codes)
<div class="ui container">
<div runat="server" id="mydiv" class="ui form">
</div>
</div>
<button onclick="myFunction()">Click me</button>
<div class="ui modal">
<i class="close icon"></i>
<div class="header">
Add request
</div>
<div class="image content">
<div class="ui form">
<label>user id</label>
<input runat="server" id="usid" type="text" />
<label>Details</label>
<textarea id="details" runat="server" rows="2"></textarea>
<label>Cost</label>
<input id="cost" runat="server" type="text" />
<label>dead time</label>
<input id="date" runat="server" class="ui date" type="date" />
</div>
</div>
<div class="actions">
<asp:Button ID="Button4" class="ui positive right labeled icon button" runat="server" OnClick="Button4_Click" Text="Button" />
<i class="checkmark icon"></i>
</div>
</div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
i use ui-semantic popup
behind code
protected void Button4_Click(object sender, EventArgs e)
{
try
{
acceptance ac = new acceptance();
ac.user_id = Convert.ToInt32(usid.Value.ToString());
ac.work_id = mywork.id;
ac.detail = details.Value.ToString();
ac.dead_time = Convert.ToDateTime(date.Value.ToString());
DataClasses1DataContext db = new DataClasses1DataContext();
var hj = from i in db.acceptances where i.user_id == ac.user_id && i.work_id == ac.work_id select i;
if (hj.Count() > 0)
{
Exception c = new Exception("this user alredy accepted");
throw c;
}
var maxValue = db.acceptances.Max(x => x.id);
ac.id = maxValue + 1;
db.acceptances.InsertOnSubmit(ac);
db.SubmitChanges();
}
catch (Exception ex)
{
HtmlGenericControl er = (HtmlGenericControl)this.Master.FindControl("error");
HtmlGenericControl al = (HtmlGenericControl)this.Master.FindControl("alert");
al.Visible = true;
er.Visible = true;
er.InnerText = ex.Message;
}
}

Why doesn't the button hit the event?

Why button doesn't hit the event ? I put a breakpoint, started with debugging but when I click it doesn't hit the event but other buttons does ? Why ?
I have also posted complete code in case you want to take a look at it.
event:
protected void btnUpdate_Click(object sender, EventArgs e)
{
try
{
if (IsPostBack && Page.IsValid)
{
if (string.IsNullOrEmpty(txtBoxContractorTypeName.Text))
{
ResultLabel.ResultLabelAttributes("Fill the required fields !", ProjectUserControls.Enums.ResultLabel_Color.Red);
return;
}
byte ID = Convert.ToByte(HdnFieldContractorTypeID.Value);
string ContractorTypeName = txtBoxContractorTypeName.Text;
if (MngContractorTypes.UpdateContractorTypes(ID, ContractorTypeName))
{
txtBoxContractorTypeName.Text = "";
ShowContractorTypes();
ResultLabel.ResultLabelAttributes("Record updated successfully !", ProjectUserControls.Enums.ResultLabel_Color.Green);
}
else
{
ResultLabel.ResultLabelAttributes("Failed !", ProjectUserControls.Enums.ResultLabel_Color.Red);
}
}
}
catch (Exception) { }
finally
{
ResultPanel.Controls.Add(ResultLabel);
}
}
Button:
<asp:Button ID="btnUpdate" ValidationGroup="0" runat="server" CssClass="btn btn-warning"
Text="Update" OnClick="btnUpdate_Click" />
Complete code:
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:UpdateProgress AssociatedUpdatePanelID="UpdatePanel1" runat="server" ID="UpdateProgress1">
<ProgressTemplate>
<div class="ajax-loading">
<div></div>
</div>
</ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div class="page-content">
<div class="row">
<div class="col-lg-12">
<center>
<asp:Panel ID="ResultPanel" runat="server">
</asp:Panel>
</center>
</div>
<div class="col-md-6">
<div class="panel">
<div class="panel-header bg-primary">
<h3><i class="fa fa-book"></i>Add Contractor Type</h3>
</div>
<div class="panel-content">
<div class="col-md-12">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">
Contractor Type
<asp:HiddenField ID="HdnFieldContractorTypeID" runat="server" />
</label>
<asp:TextBox runat="server" ID="txtBoxContractorTypeName" CssClass="form-control"></asp:TextBox>
</div>
</div>
</div>
<div class="clearfix"></div>
</div>
<div class="panel-footer clearfix">
<div class="pull-right">
<input type="button" value="Reset" onclick="Clear()" class="btn btn-success" />
<asp:Button ID="btnAddContractorType" ValidationGroup="0" runat="server" CssClass="btn btn-primary"
Text="Add" OnClick="btnAddContractorType_Click" />
<asp:Button ID="btnUpdate" runat="server" CssClass="btn btn-warning"
Text="Update" OnClick="btnUpdate_Click" Visible="false" />
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="panel fadeIn">
<div class="panel-header bg-success">
<h3><i class="fa fa-search"></i>Contractor Types</h3>
</div>
<div class="panel-content">
<div class="col-md-12">
<div class="input-group">
<label class="control-label">
Search
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Required" ForeColor="Red" ControlToValidate="txtSearch" ValidationGroup="S"></asp:RequiredFieldValidator>
</label>
<asp:TextBox runat="server" CssClass="form-control" ID="txtSearch"></asp:TextBox>
<span class="input-group-btn">
<asp:Button runat="server" ID="btnSearch" OnClick="btnSearch_Click" CssClass="btn btn-warning" Text="Search" Style="margin-top: 25px" ValidationGroup="S" />
</span>
</div>
</div>
<div class="col-md-12">
<asp:GridView runat="server" ID="grdviewContractorTypes" OnRowEditing="grdviewContractorTypes_RowEditing" OnRowCommand="grdviewContractorTypes_RowCommand" DataKeyNames="pk_ContractorTypes_ContractorTypeID" AutoGenerateColumns="false" CssClass="table table-condensed table-bordered table-striped table-responsive">
<Columns>
<asp:BoundField DataField="pk_ContractorTypes_ContractorTypeID" HeaderText="ID" />
<asp:BoundField DataField="ContractorTypeName" HeaderText="Contractor Type" />
<asp:ButtonField CommandName="edit" ImageUrl="~/assets/global/images/shopping/edit.png" ButtonType="Image" ControlStyle-Width="25px" ControlStyle-Height="25px" />
</Columns>
</asp:GridView>
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
Server code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Contractors;
public partial class MainForms_ContractorTypes : System.Web.UI.Page
{
ASP.controls_resultlabel_ascx ResultLabel = new ASP.controls_resultlabel_ascx();
Contractors.ManageContractorTypes MngContractorTypes = new ManageContractorTypes();
protected void Page_Load(object sender, EventArgs e)
{
//ASP.controls_resultlabel_ascx ResultLabel = new ASP.controls_resultlabel_ascx();
if (!IsPostBack)
{
}
}
protected void btnAddContractorType_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrEmpty(txtBoxContractorTypeName.Text))
{
ResultLabel.ResultLabelAttributes("Fill the required fields !", ProjectUserControls.Enums.ResultLabel_Color.Red);
return;
}
string ContractorTypeName = txtBoxContractorTypeName.Text;
if (MngContractorTypes.InsertContractorTypes(ContractorTypeName))
{
txtBoxContractorTypeName.Text= "";
ResultLabel.ResultLabelAttributes("Record inserted successfully !", ProjectUserControls.Enums.ResultLabel_Color.Green);
}
else
{
ResultLabel.ResultLabelAttributes("Account Already Exist !", ProjectUserControls.Enums.ResultLabel_Color.Red);
}
}
catch (Exception)
{
}
finally
{
ResultPanel.Controls.Add(ResultLabel);
}
}
protected void grdviewContractorTypes_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "edit")
{
byte ContractorTypeID = Convert.ToByte(grdviewContractorTypes.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
//HFActID.Value = ID.ToString();
btnAddContractorType.Visible = false;
btnUpdate.Visible = true;
DataTable dt = MngContractorTypes.SelectContractorTypesByContractorTypeID(ContractorTypeID);
DataRow r = dt.Rows[0];
txtBoxContractorTypeName.Text = r["ContractorTypeName"].ToString();
HdnFieldContractorTypeID.Value = r["pk_ContractorTypes_ContractorTypeID"].ToString();
//txtSearch.Text = "Testing...";
//Response.Write("DONE");
}
}
catch (Exception ex)
{
Response.Write(Convert.ToString(ex.Message));
}
}
protected void grdviewContractorTypes_RowEditing(object sender, GridViewEditEventArgs e)
{
// code to edit
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrEmpty(txtBoxContractorTypeName.Text))
{
ResultLabel.ResultLabelAttributes("Fill the required fields !", ProjectUserControls.Enums.ResultLabel_Color.Red);
return;
}
byte ID = Convert.ToByte(HdnFieldContractorTypeID.Value);
string ContractorTypeName = txtBoxContractorTypeName.Text;
if (MngContractorTypes.UpdateContractorTypes(ID, ContractorTypeName))
{
txtBoxContractorTypeName.Text = "";
ShowContractorTypes();
ResultLabel.ResultLabelAttributes("Record updated successfully !", ProjectUserControls.Enums.ResultLabel_Color.Green);
}
else
{
ResultLabel.ResultLabelAttributes("Failed !", ProjectUserControls.Enums.ResultLabel_Color.Red);
}
}
catch (Exception) { }
finally
{
ResultPanel.Controls.Add(ResultLabel);
}
}
private void ShowContractorTypes()
{
grdviewContractorTypes.DataSource = MngContractorTypes.SelectContractorTypes();
grdviewContractorTypes.DataBind();
}
protected void btnSearch_Click(object sender, EventArgs e)
{
try
{
DataTable dt = MngContractorTypes.SelectContractorTypesByContractorTypeName(txtSearch.Text.Trim());
if (dt.Rows.Count > 0)
{
grdviewContractorTypes.DataSource = dt;
grdviewContractorTypes.DataBind();
}
else
{
grdviewContractorTypes.EmptyDataText = "No Record Found";
grdviewContractorTypes.DataBind();
}
}
catch (Exception) { }
}
}
Have you copied this method from other page/application ?
If yes then it will not work.
You need to delete the event and event name assigned to the button then go to design view and go to button event properties go to onClick event double click next to it, it will generate event and it automatically assigns event name to the button.
If No,
Try to Clean your solution and then try once again.
Please refer this article
Try changing the access modifier from protected to public, this will stop the method from being called depending on your class structure.
See here for more information on access modifiers: https://msdn.microsoft.com/en-us/library/ms173121.aspx
Try enabling the AutoPostBack property of the Button.
<asp:Button ID="btnUpdate" ValidationGroup="0" runat="server" CssClass="btn btn-warning" Text="Update" OnClick="btnUpdate_Click" AutoPostBack="true" />

ASP button even not firing

I have set up a page with a submit button that the user can click and log in. I need to gather the field values and then do some backend stuff, but when the button is clicked, the even handler method I have set up doesn't fire. Heres the button code:
<asp:Button UseSubmitBehavior="false" CssClass="btn btn-primary" ID="btnTest" runat="server" Text="Submit" OnClick="btnTest_Click" />
And the codebehind:
public partial class SignIn : System.Web.UI.Page
{
protected void Page_Load(Object sender, EventArgs e)
{
btnTest.Click += new EventHandler(this.btnTest_Click);
}
protected void btnTest_Click(Object sender, EventArgs e)
{
string user = username.Value;
string pass = password.Value;
int userid = -1;
RoomSvc.Data.Person[] persons = RoomService.Service.ServiceClient.GetPersons();
RoomSvc.Data.Person pUser = null;
foreach (RoomSvc.Data.Person p in persons)
{
if (p.username == user && p.password == pass)
{
pUser = RoomService.Service.ServiceClient.GetPerson(userid.ToString());
}
else
{
return;
}
}
RoomService.Global.currentUser = pUser;
}
}
I have tried everything out there and nothing is making it work, could someone please enlighten.
EDIT: .aspx code:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="SignIn.aspx.cs" Inherits="RoomService.Account.SignIn" %>
<asp:Content ID="SignInHeader" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="SignInContent" ContentPlaceHolderID="MainContent" runat="server">
<form action="SignIn.aspx" class="form-horizontal well span5 offset5">
<fieldset>
<legend>Sign In</legend>
<div class="control-group">
<label class="control-label" for="input01">Username</label>
<div class="controls">
<input runat="server" type="text" class="input-medium" id="username" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="input01">Password</label>
<div class="controls">
<input runat="server" type="text" class="input-medium" id="password" />
</div>
</div>
<div class="form-actions">
<asp:Button CssClass="btn btn-primary" ID="btnTest" runat="server" Text="Submit" OnClick="btnTest_Click" />
</div>
</fieldset>
</form>
</asp:Content>
Your form tag is missing runat="server
I figured it out.
I had to add the even handler in Page_Init() not Page_Load()

Categories

Resources