I want to update the text property of my textbox control in Asp.Net from within loop.I have tried using Ajax updatepanel with the timer control but unable to update the text property.I have been searching this since last week but unable to find any answer any help would be higly appreciated
Following is the detail:
This is my button click event in this code you can see I am updating the
TxtContent.Text
within a loop the text is being returned by a user defined function called
ReturnBodyText()
afterwards I am assigning the text to the viewstate so that at the timer tick event I can recall the text and update the textbox text property and then at the timer tick event assigning the viewstate values to the textbox.
protected void Button4_Click(object sender, EventArgs e)
{
ArrayList FilePath = (ArrayList)ViewState["ArrayList"];
int i = 0;
int b = 1;
foreach(string[] sr in FilePath)
{
string Month = sr[i];
string datewithzero;
datewithzero = String.Format("{0:00}", b);
string[] FilesArray = (string[])listfiles(Month, datewithzero).ToArray(typeof(string));
foreach (string FileNameWithExtension in FilesArray)
{
ListBox4.Items.Add(FileNameWithExtension);
TxtContent.Text = ReturnBodyText(Month, datewithzero, FileNameWithExtension);
ViewState["Content"] = TxtContent.Text;
Timer1.Enabled = true;
Timer1_Tick(ViewState["Content"], e);
}
i = i + 1;
b = b + 1;
}
}
protected void Timer1_Tick(object sender, EventArgs e)
{
TxtContent.Text =(string) ViewState["Content"];
TxtContent.DataBind();
}
I Hope the above description will help you guys in understanding my problem
The complete aspx file and the code behind is as follows:
Aspx Code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%# Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %>
<asp:ListBox ID="ListBox1" runat="server" Height="509px" Width="59px">
</asp:ListBox>
<asp:Button ID="Button2" runat="server" Height="26px" onclick="Button2_Click"
Text="To be pressed first" Width="130px" />
<asp:Button ID="Button3" runat="server" onclick="Button3_Click"
Text="To be pressed 2nd" Width="131px" Height="26px" />
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Timer ID="Timer1" runat="server" Interval="1000"
ontick="Timer1_Tick" Enabled="False">
</asp:Timer>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:TextBox ID="TxtContent" runat="server" Height="508px" AutoPostBack="True"
TextMode="MultiLine"></asp:TextBox>
<asp:Button ID="Button5" runat="server" Height="26px" onclick="Button4_Click"
Text="To be pressed Third" Width="122px" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
</div>
</form>
- Codebehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Collections;
public partial class _Default : ftp
{
protected void Button2_Click(object sender, EventArgs e)
{
string[] array = (string[])listfiles().ToArray(typeof(string));
ViewState["FolderName"] = array;
foreach (string FileName in array)
{
ListBox1.Items.Add(FileName);
}
}
protected void Button3_Click(object sender, EventArgs e)
{
string[] arraylistbox2 = (string[])ViewState["FolderName"];
string[] arrays = new string[12];
ArrayList ListPath = new ArrayList();
int dateFolder;
foreach (string FileName in arraylistbox2)
{
dateFolder = Convert.ToInt16(FileName);
dateFolder = dateFolder - 1;
ListPath.Add((string[])(listfiles(FileName).ToArray(typeof(string))));
}
ViewState["ArrayList"] = ListPath;
}
protected void Button4_Click(object sender, EventArgs e)
{
ArrayList FilePath = (ArrayList)ViewState["ArrayList"];
int i = 0;
int b = 1;
foreach(string[] sr in FilePath)
{
string Month = sr[i];
string datewithzero;
datewithzero = String.Format("{0:00}", b);
string[] FilesArray = (string[])listfiles(Month, datewithzero).ToArray(typeof(string));
foreach (string FileNameWithExtension in FilesArray)
{
TxtContent.Text = ReturnBodyText(Month, datewithzero, FileNameWithExtension);
ViewState["Content"] = TxtContent.Text;
Timer1.Enabled = true;
Timer1_Tick(ViewState["Content"], e);
}
i = i + 1;
b = b + 1;
}
}
protected void Timer1_Tick(object sender, EventArgs e)
{
TxtContent.Text =(string) ViewState["Content"];
TxtContent.DataBind();
}
Sadly, your code did not help me much. However, I wrote this which I believe does what you want -partially-. It seems to me nothing more can be done though. Here is the code:
.aspx file:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:Timer runat="server" ID="Timer1" Interval="1000" Enabled="true"
ontick="Timer1_Tick" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
aspx.cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
protected static string keeper;
protected static bool inUse = false;
protected void Page_Load(object sender, EventArgs e) {}
protected void Button1_Click(object sender, EventArgs e)
{
Thread worker = new Thread(new ThreadStart(workerFunction));
worker.Start();
return;
}
protected void workerFunction()
{
inUse = true;
for (int i = 0; i < 3; i++)
{
TextBox1.Text += "foo";
keeper = TextBox1.Text;
Thread.Sleep(1000);
}
inUse = false;
keeper = "";
}
protected void Timer1_Tick(object sender, EventArgs e)
{
if (inUse)
{
TextBox1.Text = Convert.ToString(keeper);
}
}
}
}
Related
In an ASP.NET web form, I have two button controls and I have come across a weird scenario.
I have btnOpenAddRoleModal and btn2. when I click on btnOpenAddRoleModal, btnAddGlobalRoles becomes visible and then I click on btnAddGlobalRoles which performs some function.
Now when I press F5 to refresh the page, and because ASP.NET post-backs the page again on refresh, it does the post back as usual.
My problem is that it runs the click event handler of btnOpenAddRoleModal instead of btnAddGlobalRoles whereas the last button I clicked was btnAddGlobalRoles.
Anyone knows why this could be a case?
aspx page
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPages/MainTheme.Master" AutoEventWireup="true" CodeBehind="GlobalRoles.aspx.cs" Inherits="OPT.GlobalRoles" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<header style="overflow: auto;">
<h1 class="zs-left">Global Roles</h1>
<div class="zs-right">
<asp:Button ID="btnOpenAddRoleModal" runat="server" Text="Add User" CssClass="zs-button zs-button-action" OnClick="btnOpenAddRoleModal_Click" OnClientClick="return IncreasePostBackControlValue();" />
</div>
</header>
<section class="page-2cols" style="position: relative;">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<h2 class="zs-inner-title">Roles</h2>
<p class="zs-search-button">
<span class="zs-input-icon zs-icon-search">
<asp:Label ID="lblSearchText" runat="server" Text="Search Roles " Style="font-weight: 700"></asp:Label>
<asp:TextBox ID="txtSearchText" runat="server" CssClass="zs-input" placehoder="Enter key words to search" AutoPostBack="True" OnTextChanged="txtSearchText_TextChanged"></asp:TextBox>
</span>
</p>
<p>
<asp:Label ID="lblMessage" runat="server" Text=""></asp:Label></p>
<p>
<asp:Label ID="lblNoResultsMessage" runat="server" Text="No results found" Visible="false"></asp:Label></p>
<p>
<asp:GridView ID="gvGlobalRoles" runat="server" AutoGenerateColumns="False" OnRowDeleting="gvGlobalRoles_RowDeleting" CssClass="zs-data-table">
<Columns>
<asp:BoundField DataField="Serial" HeaderText="Sr. No." />
<asp:BoundField DataField="EmployeeName" HeaderText="Employee Name" />
<asp:BoundField DataField="RoleName" HeaderText="Role" />
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<span class="zs-icon zs-icon-delete"></span>
<asp:LinkButton Text="Delete" CommandName="Delete" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</p>
<asp:Panel ID="pnlOverlay" CssClass="zs-overlay" Visible="false" runat="server"></asp:Panel>
<asp:Panel ID="pnlModal" Visible="false" CssClass="zs-modal" Style="display: inline-block; position: fixed; top: 50%; left: 50%; margin-top: 0px; margin-left: 0px; transform: translate(-50%, -50%);" runat="server">
<header>
<span><% =ModalTitle %></span>
<asp:LinkButton ID="lbCloseModal" runat="server" CssClass="zs-icon zs-icon-close zs-icon-large" OnClick="lbCloseModal_Click"></asp:LinkButton>
</header>
<section>
<p>
<asp:Label ID="lblModalMessage" runat="server" Text=""></asp:Label></p>
<asp:Panel ID="pnlDeleteListItem" runat="server" Visible="false">
You have selected to delete a role. Press OK to continue or Cancel to abort.
</asp:Panel>
<asp:Panel ID="pnlAddEditListItem" runat="server" Visible="false">
<p>
<asp:Label ID="lblEmployeeToAdd" runat="server" Text="Employee Email"></asp:Label><br />
<asp:TextBox ID="txtEmployeeToAdd" runat="server" CssClass="zs-input"></asp:TextBox>
</p>
<p>
<asp:Label ID="lblRoleToAdd" runat="server" Text="Role"></asp:Label><br />
<asp:DropDownList ID="ddlRoleToAdd" runat="server" CssClass="zs-input"></asp:DropDownList>
</p>
</asp:Panel>
</section>
<footer>
<asp:LinkButton ID="lbCancelModal" runat="server" OnClick="lbCancelModal_Click">Cancel</asp:LinkButton>
<asp:Button ID="btnAddGlobalRoles" runat="server" Text="Add" CssClass="zs-button zs-button-action" OnClick="btnAddGlobalRoles_Click" OnClientClick="return IncreasePostBackControlValue();" Visible="false" />
<asp:Button ID="btnDeleteGlobalRole" runat="server" CssClass="zs-button zs-button-action" Text="OK" OnClick="btnDeleteGlobalRole_Click" OnClientClick="return IncreasePostBackControlValue();" Visible="false" />
</footer>
</asp:Panel>
<asp:HiddenField ID="hfPostBackControl" runat="server" ClientIDMode="Static" />
<script>
//$(document).on("click", "button,input[type='submit'],input[type='button']", function () {
// $("#hfPostBackControl").val($("#hfPostBackControl").val() == "" ? 1 : Number($("#hfPostBackControl").val()) + 1);
//});
function IncreasePostBackControlValue() {
$("#hfPostBackControl").val($("#hfPostBackControl").val() == "" ? 1 : Number($("#hfPostBackControl").val()) + 1);
return true;
}
</script>
</ContentTemplate>
</asp:UpdatePanel>
</section>
</asp:Content>
aspx.cs page
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 OPT.Models;
namespace OPT
{
public partial class GlobalRoles : System.Web.UI.Page
{
BAL bal = new BAL();
string message = "";
int messageStateID;
DataTable dtRoles;
DataTable dtGlobalEmployeeRoles;
GlobalRole globalRoleToDelete;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadRoleDropDown();
LoadGlobalRolesFromDatabase();
Session["sPostBackValue"] = 0;
}
Generic.HideControls(AllMessageControls);
}
protected void Page_PreInit(object sender, EventArgs e)
{
Session["CurrentPage"] = ePage.GlobalRoles;
}
protected void Page_LoadComplete(object sender, EventArgs e)
{
if (!Pages.ShowGlobalRoles())
{
Generic.RediretToMesagePage("Unauthorized user");
}
if (gvGlobalRoles.Rows.Count > 0)
{
gvGlobalRoles.HeaderRow.TableSection = TableRowSection.TableHeader;
lblNoResultsMessage.Visible = false;
}
else
{
lblNoResultsMessage.Visible = true;
}
}
void LoadGlobalRolesFromDatabase()
{
dtGlobalEmployeeRoles = bal.GetGlobalEmployeeRoles(txtSearchText.Text, ref message, ref messageStateID);
Session["GlobalEmployeeRoles"] = dtGlobalEmployeeRoles;
gvGlobalRoles.DataSource = Session["GlobalEmployeeRoles"] as DataTable;
gvGlobalRoles.DataBind();
}
void LoadRoleDropDown()
{
dtRoles = bal.GetGlobalRoles(ref message, ref messageStateID);
Generic.PopulateDataTableInDropDown(ddlRoleToAdd, dtRoles, "ID", "Name", "Please select");
}
protected void gvGlobalRoles_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int rowIndex = e.RowIndex;
globalRoleToDelete = new GlobalRole();
dtGlobalEmployeeRoles = Session["GlobalEmployeeRoles"] as DataTable;
globalRoleToDelete.ID = Convert.ToInt32(dtGlobalEmployeeRoles.Rows[rowIndex]["ID"].ToString());
Session["CurrentGlobalRole"] = globalRoleToDelete;
ModalTitle = "Delete Role";
Generic.ShowControls(modalDeleteControls);
}
protected void btnAddGlobalRoles_Click(object sender, EventArgs e)
{
if (Generic.IsRefresh(hfPostBackControl)) { return; }
Employee employee = new Employee();
Role role = new Role();
employee.EmailID = txtEmployeeToAdd.Text;
role.ID = Convert.ToInt32(ddlRoleToAdd.SelectedValue);
bal.CreateGlobalEmployeeRole(employee, role, ref message, ref messageStateID);
if (messageStateID == 1)
{
Generic.HideControls(modalAllControls);
Generic.ShowMessage(lblMessage, message, messageStateID);
}
else
{
ModalTitle = eModalTitle.EditProject;
Generic.ShowMessage(lblModalMessage, message, messageStateID);
}
LoadGlobalRolesFromDatabase();
}
protected void btnDeleteGlobalRole_Click(object sender, EventArgs e)
{
if (Generic.IsRefresh(hfPostBackControl)) { return; }
globalRoleToDelete = Session["CurrentGlobalRole"] as GlobalRole;
bal.DeleteGlobalEmployeeRole(globalRoleToDelete, ref message, ref messageStateID);
if (messageStateID == 1)
{
Generic.HideControls(modalAllControls);
Generic.ShowMessage(lblMessage, message, messageStateID);
}
else
{
ModalTitle = eModalTitle.EditProject;
Generic.ShowMessage(lblModalMessage, message, messageStateID);
}
LoadGlobalRolesFromDatabase();
Generic.HideControls(modalDeleteControls);
}
protected void lbCloseModal_Click(object sender, EventArgs e)
{
Generic.HideControls(modalAllControls);
}
protected void lbCancelModal_Click(object sender, EventArgs e)
{
Generic.HideControls(modalAllControls);
}
protected void btnOpenAddRoleModal_Click(object sender, EventArgs e)
{
if (Generic.IsRefresh(hfPostBackControl)) { return; }
ModalTitle = "Add Role";
Generic.ClearControlValuesInContainer(pnlAddEditListItem);
Generic.ShowControls(modalAddControls);
}
protected void txtSearchText_TextChanged(object sender, EventArgs e)
{
LoadGlobalRolesFromDatabase();
}
private string _ModalTitle;
public string ModalTitle
{
get { return _ModalTitle; }
set { _ModalTitle = value; }
}
protected List<Control> modalAllControls
{
get
{
List<Control> controls = new List<Control>();
controls.AddRange(modalGenericControls);
controls.AddRange(modalAddControls);
controls.AddRange(modalDeleteControls);
return controls;
}
}
protected List<Control> modalGenericControls
{
get
{
return new List<Control>{
pnlOverlay as Control,
pnlModal as Control
};
}
}
protected List<Control> modalDeleteControls
{
get
{
List<Control> controls = new List<Control>{
pnlDeleteListItem as Control,
btnDeleteGlobalRole as Control
};
controls.AddRange(this.modalGenericControls);
return controls;
}
}
protected List<Control> modalAddControls
{
get
{
List<Control> controls = new List<Control>{
pnlAddEditListItem as Control,
btnAddGlobalRoles as Control
};
controls.AddRange(this.modalGenericControls);
return controls;
}
}
protected List<Control> AllMessageControls
{
get
{
List<Control> messageControls = new List<Control>{
lblMessage as Control,
lblModalMessage as Control
};
return messageControls;
}
}
}
}
Few supporting methods here
public static bool IsRefresh(HiddenField hfPostBackControl)
{
int sPostBackValue = HttpContext.Current.Session["sPostBackValue"] == null ? 0 : Convert.ToInt32(HttpContext.Current.Session["sPostBackValue"]);
int hPostBackValue = string.IsNullOrEmpty(hfPostBackControl.Value) ? 0 : Convert.ToInt32(hfPostBackControl.Value);
HttpContext.Current.Session["sPostBackValue"] = hPostBackValue;
return sPostBackValue == hPostBackValue;
}
/// <summary>
/// This method can be used for displaying pop ups after any action. One needs to pass the controls as parameter that need to shown on any event.
/// </summary>
/// <param name="controls">List of controls that need to be displyed as pop-up</param>
public static void ShowControls(List<Control> controls)
{
foreach (Control c in controls)
{
c.Visible = true;
}
}
/// <summary>
/// This method can be used for hiding pop ups being displayed. One needs to pass the controls as parameter that need to hidden on any event.
/// </summary>
/// <param name="controls">List of controls that need to be hidden</param>
public static void HideControls(List<Control> controls)
{
foreach (Control c in controls)
{
c.Visible = false;
}
}
public static void ShowMessage(Label lblMessage, string message, int messageStateID)
{
lblMessage.Text = message;
lblMessage.CssClass = messageStateID == 1 ? "zs-message zs-success" : "zs-message zs-error";
lblMessage.Visible = true;
}
Here is the following complete code
1) is the master page aspx
2) is the webform page aspx
3) is the webform C# file
The complete details as i suppose
now this ASP:content is already a form and also when i am adding form tag it is showing the page can have only form tage .Please can anyone help ?
Master page
<%# Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="eliblogin" runat="server" Text="Login"></asp:Label>
</form>
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</body>
</html>
masterpage.cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class MasterPage : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
Page.LoadComplete += new EventHandler(set_button);
}
protected void eliblogout_Click(object sender, EventArgs e)
{
var user = Context.User.Identity;
//authentication manager
var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
//logout
authenticationManager.SignOut();
Response.Redirect("~/Index.aspx");
}
private void set_button(Object sender,EventArgs e)
{
var user = Context.User.Identity;
if (user.Name!=null && user.IsAuthenticated)
{
try
{
//Username.Text = user.Name;
eliblogin.Visible = true;
eliblogin.Text = "yes man you did it";
// eliblogout.Visible = true;
}
catch (Exception ex)
{
//Username.Text = ex.ToString();
}
}
else
{
// Username.Text = "Hello Guest";
eliblogin.Visible = true;
// eliblogout.Visible = false;
}
}
}
Login.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Pages_Account_Login" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:Label ID="liStatus" runat="server"></asp:Label>
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="username"></asp:Label><br />
<br />
<asp:TextBox ID="txtUsername" runat="server"></asp:TextBox>
<br />
<asp:Label ID="Label2" runat="server" Text="Password"></asp:Label><br />
<br />
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password"> </asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Login" OnClick="Button1_Click" />
</asp:Content>
login.aspx.cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
public partial class Pages_Account_Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
//User Store
UserStore<IdentityUser> userStore = new UserStore<IdentityUser>();
userStore.Context.Database.Connection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["elibraryConnectionString"].ConnectionString;
//User Manager
UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore);
//Create a new User
var user = manager.Find(txtUsername.Text,txtPassword.Text);
if (user!=null)
{
try
{
//Create user Object
//Database will be created Automatically
var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
var userIdentity = manager.CreateIdentity(user,DefaultAuthenticationTypes.ApplicationCookie);
authenticationManager.SignIn(new AuthenticationProperties
{
IsPersistent=false
},userIdentity);
}
catch (Exception ex)
{
liStatus.Text = ex.ToString();
}
}
else
{
liStatus.Text = "invalid username or password";
}
}
catch (Exception ex)
{
liStatus.Text = ex.ToString();
}
}
}
You should move
<form id="form1" runat="server">
<asp:Label ID="eliblogin" runat="server" Text="Login"></asp:Label>
</form>
from master page to login.aspx page and place all asp content of login page into this form tag.
How Can I Add One Event to Each item On A CheckBoxList, pr example I Wanto to add One Click Event to check What Item Has been checked.
thanks in advance.
Each item in CheckBoxList is of type System.Web.UI.WebControls.ListItem and has no events defined.
That's a bit tricky with the CheckBoxList. Don't think there's a straight way to add an click-event to each item, since the ListItem-class doesn't have any events.
You could set AutoPostBack="true" on the CheckBoxList and check on page load which items are selected, but you wouldn't know easy which was the last one clicked.
Other solution is to get rid of the CheckBoxList and create just CheckBoxes and set the click-event on those to the same event-method. And there you could check the sender.
ASPX:
<asp:CheckBox ID="CheckBox1" Text="A" OnCheckedChanged="CheckBox_Clicked" AutoPostBack="true" runat="server" />
<asp:CheckBox ID="CheckBox2" Text="B" OnCheckedChanged="CheckBox_Clicked" AutoPostBack="true" runat="server" />
<asp:CheckBox ID="CheckBox3" Text="C" OnCheckedChanged="CheckBox_Clicked" AutoPostBack="true" runat="server" />
Code behind:
void CheckBox_CheckedChanged(object sender, EventArgs e)
{
Console.WriteLine(((CheckBox)sender).Text);
}
Or you could make your own custom CheckBoxList that handles click-events on items.
OK. So I found this question/answer and it didn't help me out. While the provided answer is correct, there is an easy way to build a CheckBoxList-like control witha Repeater control.
Turns out that you can use a Repeater with an ItemTemplate with a CheckBox.
I have a complete explanation here: http://www.rhyous.com/2014/10/17/aspx-checkboxlist-alternative-that-allows-for-the-oncheckedchanged-event/
I also copied the needed data here in this answer:
Default.aspx
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CheckBoxListExample._Default" %>
<%# Import Namespace="CheckBoxListExample" %>
<%# Import Namespace="CheckBoxListExample.Models" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<div>
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:CheckBox ID="cb1" runat="server" AutoPostBack="true" OnCheckedChanged="RepeaterCheckBoxChanged"
Text="<%# ((CheckBoxViewModel)Container.DataItem).Name %>"
Checked="<%# ((CheckBoxViewModel)Container.DataItem).IsChecked %>" />
</ItemTemplate>
</asp:Repeater>
</div>
</asp:Content>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using CheckBoxListExample.Models;
namespace CheckBoxListExample
{
public partial class _Default : Page
{
private List<CheckBoxViewModel> _ViewModels;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var _ViewModels = new List<CheckBoxViewModel>
{
new CheckBoxViewModel {Name = "Test1", IsChecked = true},
new CheckBoxViewModel {Name = "Test2"},
new CheckBoxViewModel {Name = "Test3"}
};
Repeater1.DataSource = _ViewModels;
Repeater1.DataBind();
}
}
protected void RepeaterCheckBoxChanged(object sender, EventArgs e)
{
var cb = sender as CheckBox;
if (cb == null) return;
if (cb.Checked)
{
// Insert
}
else
{
// Delete
}
}
}
}
CheckBoxViewModel
namespace CheckBoxListExample.Models
{
public class CheckBoxViewModel
{
public string Name { get; set; }
public bool IsChecked { get; set; }
}
}
I want to refresh a GridView after selecting values in an AJAX ModalPopup. But the refresh happens only after clicking again on the select button. The refresh should happen straight after click on OK... What do I am wrong?
Greets
Marco
<div id="container" runat="server" />
<input id="dummy" type="button" style="display:none" runat="server"/>
<ajaxToolkit:ModalPopupExtender runat="server"
ID="mpeThePopup"
TargetControlID="dummy"
PopupControlID="pnlModalPopUpPanel"
DropShadow="true"/>
<asp:Panel ID="pnlModalPopUpPanel" runat="server">
<asp:UpdatePanel ID="updatePanel2" runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:ListBox ID="availableCategories" runat="server" DataTextField="CategoryName" DataValueField="CategoryID" SelectionMode="Multiple"/>
<asp:Button ID="moveRight" runat="server" Text=">" OnClick="moveRightClick" />
<asp:Button ID="moveLeft" runat="server" Text="<" OnClick="moveLeftClick" />
<asp:ListBox ID="selectedCategories" runat="server" DataTextField="CategoryName" DataValueField="CategoryID" SelectionMode="Multiple"/>
<asp:Button ID="okButton" runat="server" Text="OK" OnClick="okClick" />
<asp:Button ID="cancelButton" runat="server" Text="Cancel" OnClick="cancelClick" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="okButton" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</asp:Panel>
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Objects;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication2
{
public partial class Select : System.Web.UI.UserControl
{
private ObjectSet<Category> osCategories;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
NorthwindEntities northwindEntities = new NorthwindEntities();
categories.DataSource = northwindEntities.Categories;
availableCategories.DataSource = northwindEntities.Categories;
DataBind();
}
Button showModal = new Button();
showModal.Text = "Select";
showModal.Click += new EventHandler(showModal_Click);
container.Controls.Add(showModal);
}
void showModal_Click(object sender, EventArgs e)
{
mpeThePopup.Show();
}
protected void moveRightClick(object sender, EventArgs e)
{
foreach(ListItem listItem in availableCategories.Items)
{
if(listItem.Selected)
{
selectedCategories.Items.Add(listItem);
//availableCategories.Items.Remove(listItem);
}
}
}
protected void moveLeftClick(object sender, EventArgs e)
{
foreach(ListItem listItem in selectedCategories.Items)
{
if(listItem.Selected)
{
availableCategories.Items.Add(listItem);
//selectedCategories.Items.Remove(listItem);
}
}
}
protected void okClick(object sender, EventArgs e)
{
categories.DataSource = null;
categories.DataBind();
categories.DataSource = availableCategories.SelectedItem;
categories.DataBind();
mpeThePopup.Hide();
}
protected void cancelClick(object sender, EventArgs e)
{
mpeThePopup.Hide();
}
}
}
Place your categories GridView inside an UpdatePanel with a Click AsyncPostBackTrigger on the okButton.
EDIT
Fixed the problem - I needed to add the validators to a ValidationGroup and then call each of the validation controls Validate() method on the submit behaviour of the button.
protected void btnDone_Click(object sender, EventArgs e)
{
this.cvValidation.Validate();
this.revYear.Validate();
if (Page.IsValid)
{
DateTime sub = Convert.ToDateTime(String.Format("01/{0}/{1}", ddlMonth.SelectedValue, txtYear.Text));
string str = sub.ToString("MMMM") + " " + sub.ToString("yyyy");
pcePopUp.Commit(str);
}
}
I am trying to add a CustomValidator to my UserControl but I cannot get the validator to run as it should. What I am trying to achieve is to test to see if the month/year is in the future.
After breaking into the code I have noticed that the validateDate method is being fired twice. Any help on this situation would be greatly appreciated.
Could it be a problem with the way I am retrieving data from the controls as using the following two methods.
private void loadPostBackData()
{
loadPostBackDataItem(((TextBox)puymcStartDate.FindControl("txtDate")));
loadPostBackDataItem(((TextBox)puymcEndDate.FindControl("txtDate")));
}
private void loadPostBackDataItem(TextBox control)
{
string controlId = control.ClientID.Replace("_", "$");
string postedValue = Request.Params[controlId];
if (!String.IsNullOrEmpty(postedValue))
{
control.Text = postedValue;
}
else
{
control.Text = String.Empty;
}
}
UserControl code
ASP.NET Code
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="CtrlPopUpYearMonthCalendar.ascx.cs" Inherits="CLIck10.Controls.CtrlPopUpYearMonthCalendar" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
<asp:TextBox ID="txtDate" ReadOnly="true" runat="server" />
<div id="divPopUp" runat="server" class="box" style="width:320px;visibility:hidden;margin-left:5px;">
<div class="boxTitle">
<h1>Choose date</h1>
</div>
<div style="padding:5px;">
<asp:UpdatePanel id="upPopUp" UpdateMode="Always" runat="server">
<ContentTemplate>
<asp:DropDownList ID="ddlMonth" runat="server" /> <asp:TextBox ID="txtYear" runat="server" />
<asp:Button ID="btnDone" Text="Done" runat="server" UseSubmitBehavior="false" onclick="btnDone_Click" />
<asp:RegularExpressionValidator ID="revYear" ValidationExpression="^[0-9]{4}$" ControlToValidate="txtYear" Display="Dynamic" Text="(*)" ErrorMessage="Year must be valid" runat="server" />
<asp:CustomValidator ID="cvValidation" Text="(*)" Display="Dynamic" ErrorMessage="Date must be in the future" OnServerValidate="validateDate" ValidateEmptyText="true" runat="server" />
<asp:ValidationSummary ID="vsDate" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
<ajaxToolkit:PopupControlExtender ID="pcePopUp" PopupControlID="divPopUp" TargetControlID="txtDate" Position="Right" runat="server" />
Code Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxControlToolkit;
using System.Diagnostics;
namespace CLIck10.Controls
{
public partial class CtrlPopUpYearMonthCalendar : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DateTime month = Convert.ToDateTime("01/01/2000");
for (int i = 0; i < 12; i++)
{
DateTime nextMonth = month.AddMonths(i);
ListItem item = new ListItem();
item.Text = nextMonth.ToString("MMMM");
item.Value = nextMonth.Month.ToString();
ddlMonth.Items.Add(item);
}
if (txtDate.Text.Equals(String.Empty))
{
ddlMonth.Items.FindByValue(DateTime.Now.AddMonths(1).Month.ToString()).Selected = true;
if (DateTime.Now.Month.ToString("MM").Equals("12"))
{
txtYear.Text = DateTime.Now.AddYears(1).ToString("yyyy");
}
else
{
txtYear.Text = DateTime.Now.ToString("yyyy");
}
}
else
{
DateTime date = Convert.ToDateTime("01, " + txtDate.Text);
ddlMonth.Items.FindByValue(date.Month.ToString()).Selected = true;
txtYear.Text = date.ToString("yyyy");
}
}
}
protected void btnDone_Click(object sender, EventArgs e)
{
DateTime sub = Convert.ToDateTime(String.Format("01/{0}/{1}", ddlMonth.SelectedValue, txtYear.Text));
string str = sub.ToString("MMMM") + " " + sub.ToString("yyyy");
pcePopUp.Commit(str);
}
public void validateDate(object sender, ServerValidateEventArgs e)
{
DateTime sub = Convert.ToDateTime(String.Format("01/{0}/{1}", ddlMonth.SelectedValue, txtYear.Text));
if (sub >= DateTime.Now)
{
e.IsValid = true;
}
else
{
e.IsValid = false;
}
}
}
}
After experimenting with just embedding the control in a blank page It works so it must be something to do with the page I am working on.
I tried out your code as a page (not a usercontrol) and it worked fine.
Are you dynamically adding your usercontrols to the page?