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()
Related
<%# 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";
}
}
I'm getting this error, but I just can't tell where it might be coming from. The line that the error page is referencing is:
# Page Title="" Language="C#" MasterPageFile="~/CV.Master" AutoEventWireup="true" CodeBehind="AddPost.aspx.cs" Inherits="CV_Blog_WDW.AddPost"
But I can't see how that line can cause that error? Unless there's something I'm missing?
My .aspx code is:
<%# Page Title="" Language="C#" MasterPageFile="~/CV.Master" AutoEventWireup="true" CodeBehind="AddPost.aspx.cs" Inherits="CV_Blog_WDW.AddPost" %>
<asp:Content ID="Content1"
ContentPlaceHolderID="ContentPlaceHolder1"
runat="server">
<!-- =========
Special Nav for BLog page
===================================-->
<nav class="nav-blog">
<a href="default.aspx"
class="btn btn-left"
data-toggle="tooltip"
data-placement="left"
title=""
data-original-title="Home">
<i class="fa fa-home"></i>
</a>
<a href="#"
class="btn btn-big-blog">Blog</a>
<a href="#"
class="btn btn-right"
data-toggle="tooltip"
data-placement="right"
title=""
data-original-title="Reload Page">
<i class="fa fa-refresh"></i>
</a>
</nav>
<!-- =========
Start Show Yor Name Section
===================================-->
</div>
</header>
<!-- =========
End portrait section
===================================-->
<!-- =========
Start Content section
===================================-->
<section class="content open"
id="main-content">
<div class="body-content"
id="blog">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="blog-posts">
<div class="blog-post">
<h3 class="title with-icon">
<span class="fa fa-comment-o icn-title"></span> Add A Post
</h3>
<div class="box-block">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="Title">Title</label>
<asp:TextBox ID="Title"
runat="server"
CssClass="form-control"></asp:TextBox>
</div>
<div class="form-group">
<label for="FeaturedImage">Featured Image</label>
<asp:FileUpload ID="FeaturedImage"
runat="server"
CssClass="form-control" />
</div>
</div>
</div>
<div class="form-group">
<label for="MesageForm">Body</label>
<asp:TextBox ID="Body"
TextMode="MultiLine"
Rows="8"
runat="server"
CssClass="form-control"></asp:TextBox>
</div>
<asp:Button id="btnAdd"
runat="server"
CssClass="btn btn-flat btn-lg"
Text="Add Post"
OnClick="btnAdd_Click" />
</div>
</div>
</div>
</div>
</div>
</div>
</asp:Content>
And my code behind is:
public partial class AddPost : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnAdd_Click(object sender, EventArgs e)
{
if(FeaturedImage.HasFile)
{
try
{
string filename = Path.GetFileName(FeaturedImage.FileName);
FeaturedImage.SaveAs(Server.MapPath("~/assets/images/blog/") + filename);
}
catch(Exception ex)
{
string error = ex.Message;
}
}
try
{
string connection = WebConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection con = new SqlConnection(connection);
SqlCommand cmd = new SqlCommand("AddPost", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Title", Title.Text);
cmd.Parameters.AddWithValue("#Date", DateTime.Now);
cmd.Parameters.AddWithValue("#FeatureImage", Path.GetFileName(FeaturedImage.FileName));
cmd.Parameters.AddWithValue("#PostedBy", 1);
cmd.Parameters.AddWithValue("#Body", Body.Text);
con.Open();
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
}
}
}
I've google'ed the error but there's nothing that seems relevant to my code? Really stumped on this one, not been able to try any fixes as to be honest not sure where to start. As far as I can see I'm not making a conversion, but maybe there's one going on that I'm, not aware of?
The error comes from assigning a string to a TextBox variable. The usual reason is that one forgets the Text property, and use something like:
MyTextbox = "Some string";
intead of:
MyTextbox.Text = "Some string";
However, as there is no such code in your methods, and because the error message points to the aspx page, the error is somewhere in the code that is generated from the markup.
You have a text box named Title. There is already a string property by that name in the Page class, and when the generated code tries to set the string property, the assigment will use the TextBox field instead as it shadows the string property.
Rename the Title text box to something that isn't used already.
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" />
I have a page that I would like to display a calendar of events that is stored in a MySQL database. I am pulling the events using asp:SqlDataSource and asp:Repeater. I am able to pull the events but I can't get the events to be sorted into the specific day. I"m using a asp:LinkButton with an OnClick event handler, but it doesn't seem to be firing when the LinkButton is clicked. I have included my code below. Any help on what i'm doing wrong and why my OnClick event isn't firing will be greatly appreciated./
ascx - page
<div class="Calendar_Container">
<ul class="Calendar_Tabs">
<li><asp:LinkButton runat="server" Text="All<br /> Week" OnClick="ShowEvents" CommandArgument="9"></asp:LinkButton></li>
<li class="Calendar_Active"><asp:LinkButton runat="server" Text="Sun<br />Nov 1" OnClick="ShowEvents" CommandArgument="1"></asp:LinkButton></li>
<li><asp:LinkButton runat="server" Text="Fri<br />Nov 6" OnClick="ShowEvents" CommandArgument="6"></asp:LinkButton></li>
</ul>
</div>
<div class="Calendar_Content">
<div id="Calendar_AllWeek" class="Calendar_Tab">
<asp:SqlDataSource runat="server" ID="sqlGetEventsAllWeek" />
<asp:Repeater runat="server" ID="rptGetEventsAllWeek" DataSourceID="sqlGetEventsAllWeek">
<ItemTemplate>
<div class="Calendar_Item">
<div class="Calendar_ItemInfo">
<div class="Calendar_ItemTitle">
<h4><a href='<%# Eval("link") %>'><%# Eval("title") %></a></h4><br />
<strong><%# Eval("event_start_time") %> <%# Eval("event_end_time") %><br /><%# Eval("event_location") %></strong><br /></div>
<div class="Calendar_ItemDescription">
<p><%#System.Web.HttpUtility.HtmlDecode(Eval("description").ToString()) %><br />
<%# Eval("event_day") %>
</p>
</div>
</div>
<div class="clear_float"> </div>
</div>
</ItemTemplate>
<SeparatorTemplate><hr /></SeparatorTemplate>
</asp:Repeater>
</div>
<div id="Calendar_EventsSun" class="Calendar_Tab">
<asp:SqlDataSource runat="server" ID="sqlGetEventSun" />
<asp:Repeater runat="server" ID="rptGetEventSun" DataSourceID="sqlGetEventSun">
<ItemTemplate>
<div class="Calendar_Item">
<div class="Calendar_ItemInfo">
<div class="Calendar_ItemTitle">
<h4><a href='<%# Eval("link") %>'><%# Eval("title") %></a></h4><br />
<strong><%# Eval("event_start_time") %> <%# Eval("event_end_time") %><br /><%# Eval("event_location") %></strong><br /></div>
<div class="Calendar_ItemDescription">
<p><%# System.Web.HttpUtility.HtmlDecode(Eval("description").ToString()) %>
<br /><strong><%# Eval("event_day") %></strong>
</p>
</div>
</div>
<div class="clear_float"> </div>
</div>
</ItemTemplate>
<SeparatorTemplate><hr /></SeparatorTemplate>
</asp:Repeater>
</div>
<div id="Calendar_EventsFri" class="Calendar_Tab">
<asp:SqlDataSource runat="server" ID="sqlGetEventFri" />
<asp:Repeater runat="server" ID="rptGetEventFri" DataSourceID="sqlGetEventFri">
<ItemTemplate>
<div class="Calendar_Item">
<div class="Calendar_ItemInfo">
<div class="Calendar_ItemTitle">
<h4><a href='<%# Eval("link") %>'><%# Eval("title") %></a></h4>
<strong><%# Eval("event_start_time") %> <%# Eval("event_end_time") %><br /><%# Eval("event_location") %></strong><br />
</div>
<div class="Calendar_ItemDescription">
<p><%# System.Web.HttpUtility.HtmlDecode(Eval("description").ToString()) %>
<br /><strong><%# Eval("event_day") %></strong>
</p>
</div>
</div>
<div class="clear_float"> </div>
</div>
</ItemTemplate>
<SeparatorTemplate><hr /></SeparatorTemplate>
</asp:Repeater>
</div>
</div>
ascx.cs - code behind
namespace Christoc.Modules.Calendar {
public partial class View : CalendarModuleBase, IActionable
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
GetAllWeek("9");
GetHomecomingWeekSun("1");
GetHomecomingWeekFri("6");
}
}
catch (Exception exc) //Module failed to load
{
Exceptions.ProcessModuleLoadException(this, exc);
}
}
protected void ShowEvents(object sender, EventArgs e)
{
string dayId = ((LinkButton)sender).CommandArgument;
GetAllWeek(dayId);
GetHomecomingWeekSun(dayId);
GetHomecomingWeekFri(dayId);
}
private void GetAllWeek(string dayId)
{
sqlGetEventsAllWeek.ConnectionString = stampConnStr;
sqlGetEventsAllWeek.ProviderName = stampProvName;
sqlGetEventsAllWeek.SelectCommand = string.Format(#"
SELECT *
FROM homecoming_program
WHERE event_day = ?
ORDER BY event_day DESC;");
sqlGetEventsAllWeek.SelectParameters.Clear();
sqlGetEventsAllWeek.SelectParameters.Add(#"day_id", dayId);
rptGetEventsAllWeek.DataBind();
}
private void GetHomecomingWeekSun(string dayId)
{
sqlGetEventSun.ConnectionString = stampConnStr;
sqlGetEventSun.ProviderName = stampProvName;
sqlGetEventSun.SelectCommand = string.Format(#"
SELECT *
FROM homecoming_program
WHERE event_day = ?
ORDER BY event_day DESC;");
sqlGetEventSun.SelectParameters.Clear();
sqlGetEventSun.SelectParameters.Add(#"day_id", dayId);
rptGetEventSun.DataBind();
}
private void GetHomecomingWeekFri(string dayId)
{
sqlGetEventFri.ConnectionString = stampConnStr;
sqlGetEventFri.ProviderName = stampProvName;
sqlGetEventFri.SelectCommand = string.Format(#"
SELECT *
FROM homecoming_program
WHERE event_day = ?
ORDER BY event_day DESC;");
sqlGetEventFri.SelectParameters.Clear();
sqlGetEventFri.SelectParameters.Add(#"day_id", dayId);
rptGetEventFri.DataBind();
}
}
}
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".