strange behaviour of asplistbox - c#

first I checked every word here :
Click questions/6621510
My problem description:
I have the next design :
<asp:UpdatePanel ID="updPnltmpTermCats" runat="server" UpdateMode="Conditional" >
<ContentTemplate>
<div class="alt">
<div class="msgnoteborder">
<div class="panelistbox">
<asp:ListBox ID="lsttmpTermCats" runat="server" DataValueField="ProposalTermCatID" DataTextField="TermCatName"
Rows="10" SelectionMode="Single" AutoPostBack="true" OnSelectedIndexChanged="lsttmpTermCats_SelectedIndexChanged" />
</div>
<div class="panelistbox">
<asp:ListBox ID="lstTermSubCat" runat="server" DataValueField="ProposalTermSubCatID" DataTextField="TermVirtualName"
Rows="10" SelectionMode="Single" OnDataBinding="lstTermSubCat_DataBinding" OnDataBound="lstTermSubCat_DataBound" ViewStateMode="Enabled" />
<div class="layoutbuttons">
<asp:ImageButton ID="TermSubCatUpBtn" runat="server" ImageUrl="~/Data/SiteImages/up.gif"
CommandName="up"
CommandArgument="TermSubCat"
SkinID="pageLayoutMoveUp" CssClass="btnup" />
<asp:ImageButton ID="TermSubCatDownBtn" runat="server" ImageUrl="~/Data/SiteImages/dn.gif"
CommandName="down"
CommandArgument="TermSubCat"
SkinID="pageLayoutMoveDown"
CssClass="btndown" />
</div>
</div>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
With code behind :
protected void lstTermSubCat_DataBound(object sender, EventArgs e)
{
int indx = -1;
indx = lstTermSubCat.SelectedIndex;
string txt = string.Empty;
txt = lstTermSubCat.Items[indx].Text;
lstTermSubCat.Items[indx].Text = Regex.Replace((txt).ToString(), #"<[^>]*>", String.Empty).Replace("\r\n", String.Empty).Trim();
}
protected void lstTermSubCat_DataBinding(object sender, EventArgs e)
{
// ListItem item = lstTermSubCat.Items. .Item;
int indx = -1;
indx = lstTermSubCat.SelectedIndex;
string txt = string.Empty;
txt = lstTermSubCat.Items[indx].Text;
lstTermSubCat.Items[indx].Text = Regex.Replace((txt).ToString(), #"<[^>]*>", String.Empty).Replace("\r\n", String.Empty).Trim();
}
If i put OnSelectedIndexChanged in the second listbox it will works but other events are not firing !
ok,
it is rely strange!
i made new page
simple one :
the design is :
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="testlist.aspx.cs" Inherits="UHSRFP.Features.UI.Admin.UHSRFP.Proposal.testlist" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="updPnltmpTermCats" runat="server" UpdateMode="Conditional" >
<ContentTemplate>
<asp:ListBox ID="lsttmpTermCats" runat="server"
DataValueField="ProposalTermCatID" DataTextField="TermCatName"
Rows="10" SelectionMode="Single" AutoPostBack="true"
OnSelectedIndexChanged="lsttmpTermCats_SelectedIndexChanged"
OnDataBinding="lsttmpTermCats_DataBinding"
OnDataBound="lsttmpTermCats_DataBound" />
<asp:ListBox ID="lstTermSubCat" runat="server"
DataValueField="ProposalTermSubCatID" DataTextField="TermVirtualName"
Rows="10" SelectionMode="Single" AutoPostBack="true"
OnSelectedIndexChanged="lsttmpTermCats_SelectedIndexChanged"
OnDataBinding="lstTermSubCat_DataBinding"
OnDataBound="lstTermSubCat_DataBound"
/>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
and the code behind is :
using System;
using System.IO;
using System.Web;
using System.Data;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Globalization;
using System.Web.UI.WebControls;
using System.Collections;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Web.UI.HtmlControls;
using UHSRFP.Business;
using UHSRFP.Features.UI.Helper;
using mojoPortal.Business;
using mojoPortal.Business.WebHelpers;
using mojoPortal.Web.Framework;
using mojoPortal.Web;
using mojoPortal.Web.AdminUI;
using mojoPortal.Web.Editor;
using mojoPortal.Web.UI;
using Resources;
namespace UHSRFP.Features.UI.Admin.UHSRFP.Proposal
{
public partial class testlist : System.Web.UI.Page
{
private int proposalID = 11;
private int siteid = 1;
int termCatID = -1;
protected void Page_Load(object sender, EventArgs e)
{
PopulateControls();
}
private void PopulateControls()
{
if ((this.proposalID > 0) & (!Page.IsPostBack))
{
Bind_tmpTermCatList();
//Bind_TermSubCatList();
}
}
private void Bind_tmpTermCatList()
{
lsttmpTermCats.Items.Clear();
ArrayList proposalTermCategories = ProposalTermCategory.GetArrayProposalTermCats(this.siteid, this.proposalID);
foreach (ProposalTermCategory proposalTermCategory in proposalTermCategories)
{
ListItem listItem = new ListItem(proposalTermCategory.TermCat.Coalesce(Resource.ContentNoTitle), proposalTermCategory.ProposalTermCatID.ToInvariantString());
lsttmpTermCats.Items.Add(listItem);
}
if (this.lsttmpTermCats.Items.Count > 0)
this.lsttmpTermCats.SelectedIndex = 0;
this.termCatID = int.Parse(lsttmpTermCats.SelectedValue);
ListItem item = lsttmpTermCats.Items.FindByValue(this.termCatID.ToInvariantString());
if (item != null)
{
lsttmpTermCats.ClearSelection();
item.Selected = true;
}
Bind_TermSubCatList();
}
private void Bind_TermSubCatList()
{
lstTermSubCat.Items.Clear();
ArrayList proposalTermSubCategories = ProposalTermSubCategory.GetArrayProposalTermSubCats(this.siteid, this.termCatID);
foreach (ProposalTermSubCategory proposalTermSubCategory in proposalTermSubCategories)
{
ListItem listItem = new ListItem(proposalTermSubCategory.TermSubCatDescr.Coalesce(Resource.ContentNoTitle), proposalTermSubCategory.ProposalTermSubCatID.ToInvariantString());
lstTermSubCat.Items.Add(listItem);
}
}
protected void lstTermSubCat_DataBound(object sender, EventArgs e)
{
// ListItem item = lstTermSubCat.Items. .Item;
int indx = -1;
indx = lstTermSubCat.SelectedIndex;
string txt = string.Empty;
txt = lstTermSubCat.Items[indx].Text;
lstTermSubCat.Items[indx].Text = Regex.Replace((txt).ToString(), #"<[^>]*>", String.Empty).Replace("\r\n", String.Empty).Trim();
}
protected void lstTermSubCat_DataBinding(object sender, EventArgs e)
{
// ListItem item = lstTermSubCat.Items. .Item;
int indx = -1;
indx = lstTermSubCat.SelectedIndex;
string txt = string.Empty;
txt = lstTermSubCat.Items[indx].Text;
lstTermSubCat.Items[indx].Text = Regex.Replace((txt).ToString(), #"<[^>]*>", String.Empty).Replace("\r\n", String.Empty).Trim();
}
protected void lsttmpTermCats_SelectedIndexChanged(object sender, EventArgs e)
{
this.termCatID = int.Parse(lsttmpTermCats.SelectedValue);
Bind_TermSubCatList();
}
protected void lsttmpTermCats_DataBinding(object sender, EventArgs e)
{
this.termCatID = int.Parse(lsttmpTermCats.SelectedValue);
//Bind_TermSubCatList();
}
protected void lsttmpTermCats_DataBound(object sender, EventArgs e)
{
this.termCatID = int.Parse(lsttmpTermCats.SelectedValue);
}
}
}
and still not working
the problem is that ONLY the events OnDataBinding and OnDataBound are not firing while on index change still working well !!
is there any tip here please ?
any help here will be as gift cause i spent long time trying every thing without results !!!
thanks

Remember if your controls don't have the bound data-source when the page is fully rendered they won't fire neither DataBinding nor DataBound events for you.
So you must bind the data-source either on their control properties (.aspx file) or on your Page_load event before the control fire the DataBiniding or DataBound event.
therefore you need to use DataBind() method after you set the data to your controls.
private void Bind_tmpTermCatList()
{
//your datasource code here
lsttmpTermCats.DataBind(); //bind your control here
Bind_TermSubCatList();
}
and in your sub list you will have something like this:
private void Bind_TermSubCatList()
{
// your datasource code here...
lstTermSubCat.DataBind(); //bind your sub control here
}
now you will see two events lsttmpTermCats_DataBinding and lsttmpTermCats_DataBound will fire afterwards.
Cheers

Related

Cannot put the text in input box in asp.net

I am trying to make the input box show some text in the asp.net using c#, but after I run the code behind, nothing is displayed in the input box. The ui is RadNumericTextBox uiDistance. In class, I put this.uiDistance.Text = "123"; But in the webpage after run the code. I cannot see "123" is put in the uiDistance text box. How can I fix it?
Here is my aspx UsageControl2SubControl1.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="UsageControl2SubControl1.ascx.cs" Inherits="WebControls.UsageControl2SubControl1" %>
<asp:HiddenField ID="uiRemoved" Value="false" runat="server" />
<asp:HiddenField ID="uiID" runat="server" />
<div class="form-group">
<div class="col-md-2 customColumnPadding">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<telerik:RadTextBox ID="uiToLocation" runat="server" Width="100%" AutoPostBack="true"
OnTextChanged="uiToLocation_Leave" EmptyMessage="<%$ Resources:ResourceHKEx,Arrive_To %>" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
<div class="col-md-2 customColumnPadding" id="uiColumnDistance" runat="server">
<telerik:RadNumericTextBox ID="uiDistance" runat="server" Width="100%" MinValue="0" NumberFormat-DecimalDigits="2" EmptyMessage="<%$ Resources:Resource,Distance %>" />
</div>
</div>
<div class="hr-line-dashed"></div>
And Here is my code behind: UsageControl2SubControl1.ascx.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
namespace WebControls
{
public partial class UsageControl2SubControl1 : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (Convert.ToBoolean(uiRemoved.Value))
{
this.Visible = false;
}
}
protected void uiAdd_Click(object sender, Telerik.Web.UI.ImageButtonClickEventArgs e)
{
}
protected void uiRemove_Click(object sender, Telerik.Web.UI.ImageButtonClickEventArgs e)
{
}
protected void RadComboBoxProduct_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
{
}
protected void uiAdd_Click1(object sender, ImageClickEventArgs e)
{
}
protected void uiRemove_Click1(object sender, ImageClickEventArgs e)
{
}
protected void uiToLocation_Leave(object sender, EventArgs e)
{
this.uiDistance.Text = "123";
}
}// end class
}// end namespace
Just to update your aspx code little bit
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div class="form-group">
<div class="col-md-2 customColumnPadding">
<telerik:RadTextBox ID="uiToLocation" runat="server" Width="100%" AutoPostBack="true"
OnTextChanged="uiToLocation_Leave" EmptyMessage="<%$ Resources:ResourceHKEx,Arrive_To %>" />
</div>
<div class="col-md-2 customColumnPadding" id="uiColumnDistance" runat="server">
<telerik:RadNumericTextBox ID="uiDistance" runat="server" Width="100%" MinValue="0" NumberFormat-DecimalDigits="2" EmptyMessage="<%$ Resources:Resource,Distance %>" />
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
As your textbox is only inside the update panel so, on post back only that portion is partially updated, you need to put RadNumericTextBox inside the update panel too.
Hope this will work.
You are using the wrong property. Use Value not Text
protected void uiToLocation_Leave(object sender, EventArgs e)
{
this.uiDistance.Value = "123";
}
As always, check the documentation. See: https://docs.telerik.com/devtools/aspnet-ajax/controls/numerictextbox/features/getting-and-setting-values
Your current code will works only when you tab out from uiToLocation textbox.
If you want to show it when page loads, just move your code in to Page_Load event instead uiToLocation_Leave.
protected void Page_Load(object sender, EventArgs e)
{
if (Convert.ToBoolean(uiRemoved.Value))
{
this.Visible = false;
}
this.uiDistance.Text = "123"; // it will assign when page loads.
}
If you want to load it only once when page loads, use IsPostaback, see below.
protected void Page_Load(object sender, EventArgs e)
{
if (Convert.ToBoolean(uiRemoved.Value))
{
this.Visible = false;
}
if (!IsPostBack)
{
this.uiDistance.Text = "123"; // it will assign only once when page loads.
}
}
IT seems you are using the wrong property to assign value to telerik Textbox.
Use .Value property as .Text property if for default aspx Textbox control
this.uiDistance.Value= "123"

After removing checkbox from checkboxlist, why checkbox isn't adding?

In this program I am dynamically adding CheckBox (by taking input from textbox) in CheckBoxList which itself is created dynamically.
Now when I add checkbox and remove it, everything works fine. When I again try to add checkbox, it is adding in the ArrayList as well as CheckboxList but not showing on the page.
Working on this from past 2 days but couldn't figure out. Please Help!!!
Thank You!
<!--chkboxlist.aspx-->
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Sample</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtchkboxname" runat="server" AutoPostBack="true"></asp:TextBox>
</div>
</form>
</body>
</html>
//chkboxlist.aspx.cs
using System;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class chkboxlist : System.Web.UI.Page
{
static ArrayList arlst = new ArrayList();
CheckBoxList chklst = new CheckBoxList();
protected void Page_Load(object sender, EventArgs e)
{
if (txtchkboxname.Text != "")
{
arlst.Add(txtchkboxname.Text);
txtchkboxname.Text = "";
}
chklst.DataSource = arlst;
chklst.DataBind();
chklst.AutoPostBack = true;
chklst.SelectedIndexChanged += new EventHandler(this.chklst_OnSelectedIndexChanged);
form1.Controls.Add(chklst);
}
protected void chklst_OnSelectedIndexChanged(object sender, EventArgs e)
{
arlst.RemoveAt(chklst.SelectedIndex);
chklst.DataSource = arlst;
chklst.DataBind();
}
}

Passing Value from UserControl to ParentPage control not working properly

I have create a photo gallery user control that show photographer in a fancy box.
I also use this control on several page to show page related photos. In hide photogallery user control if their are no photos for perticular page. For this i pass public event
public event SendMessageToThePageHandler showGallery;
to pass a boolean value to hide and show usercontrol on the page.
Page runs without any errors and show the gallery. But problem is with the Pager which doesn't work the way i am coded it. It generate NullReferenceException when i click on the page 2 or the gallery
I would appreeciate a more professional approach to this scenario in which i can pass passvalue to parent page correctly to hide/show correctly.
I am also using UpdatePanel in my usercontrol. Below is the sample code from Parent Page & User Control page
PageOne.aspx
<uc1:PhotoGallery ID="ucPhotoGallery" runat="server" />
CODE BEHIND
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
try
{
int _LangID = int.Parse(Helper.GetAppSettingValue("EnglishLanguageID"));
if (string.IsNullOrEmpty(Request["PID"]))
{
_LID = int.Parse(HttpContext.Current.Request.RequestContext.RouteData.Values["LID"].ToString());
_PID = int.Parse(HttpContext.Current.Request.RequestContext.RouteData.Values["PID"].ToString());
getPageDetails(_PID);
getPageSubMenus(_PID);
// WriteThisMessageToThePage1.sendMessageToThePage += delegate(string message)
ucPhotoGallery.showGallery += delegate(bool showControl)
{
bool bShowControl = showControl;
ucPhotoGallery.Visible = bShowControl;
};
}
else
{
Response.Write("Page not be found, Wrong URL");
}
}
catch (Exception ex)
{
}
}
}
Photo-Gallery.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeFile="Photo-Gallery.ascx.cs" Inherits="Photo_Gallery" %>
<%# Register Src="~/en/UserControls/PagerControl.ascx" TagName="PagerControl" TagPrefix="uc1" %>
<div class="uc-gallery-wrapper">
<div class="page-title-side-wrapper"><h5><asp:Label ID="lblPageTitleSide" CssClass="lbl-page-title-side" runat="server" Text=" Gallery"></asp:Label></h5></div>
<asp:UpdatePanel ID="updPnlAlbums" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div class="rptAlbums-wrapper">
<asp:Repeater ID="rptAlbums" runat="server" >
<ItemTemplate>
<div class="uc-album-wrapper">
<div class="uc-album-icon"><asp:Image ID="imgAlbumIcon" CssClass="uc-album-img" ImageUrl='<%# getImage(Eval("AlbumIcon")) %>' AlternateText='<%# getTitle(Eval("AlbumName")) %>' runat="server" /></div>
<div class="uc-album-name">
<asp:HyperLink ID="hylnkAlbum" CssClass="fancybox-iframe" runat="server" NavigateUrl='<%# getAID(Eval("AlbumID")) %>'>
<asp:Label ID="lblAlbumName" runat="server" Text='<%# getTitle(Eval("AlbumName")) %>'></asp:Label>
</asp:HyperLink>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
<div class="uc-gallery-pager-wrapper-o">
<div class="uc-pager-wrapper-i">
<uc1:PagerControl ID="PagerControl1" runat="server" CssClass="gold-pager" PageMode="LinkButton" />
<asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="updPnlAlbums" Visible="False">
<ProgressTemplate>
<div id="imgLoadingNewsList" class="uc-PagerLoading">
<asp:Image ID="imgLoading" runat="server" ImageUrl="~/Images/preloader-160x15.gif" Visible="false" AlternateText="loading" />
</div>
</ProgressTemplate>
</asp:UpdateProgress>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<!-- UpdatePanel -->
</div>
CODE BEHIND
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Globalization;
using System.Data;
using CMS.SqlHelper;
using CMS.DataAccessLayer;
using System.Text;
public delegate void SendMessageToThePageHandler(bool showGallery);
public partial class Photo_Gallery : System.Web.UI.UserControl
{
int _PageID = 0;
public event SendMessageToThePageHandler showGallery;
protected void Page_Load(object sender, EventArgs e)
{
PagerControl1.PagerControl_PageIndexChanged += new EventHandler(PagerControl1_PagerControl_PageIndexChanged);
Page.MaintainScrollPositionOnPostBack = false;
if (!IsPostBack)
{
if (string.IsNullOrEmpty(Request["PID"]))
{
_PageID = int.Parse(HttpContext.Current.Request.RequestContext.RouteData.Values["PID"].ToString());
//_PageID = 3;
getAlbumByPageID(3);
}
else
{
Response.Write("Page not be found, Wrong URL");
}
}
}
public void getAlbumByPageID(int _PageID)
{
PagerControl1.PageSize = 2;
PagerControl1.DisplayEntriesCount = 5;
//Will show 2 links after ...
PagerControl1.EdgeEntriesCount = 0;
DataSet ds = DataProvider.GetAlbumByPageID(_PageID);
DataView dv = ds.Tables[0].DefaultView;
if (ds.Tables[0].Rows.Count > 0)
{
showGallery(true);
}
else
{
showGallery(false);
}
//pass the datatable and control to bind
PagerControl1.BindDataWithPaging(rptAlbums, dv.Table);
}
void PagerControl1_PagerControl_PageIndexChanged(object sender, EventArgs e)
{
_PageID = int.Parse(HttpContext.Current.Request.RequestContext.RouteData.Values["PID"].ToString());
getAlbumByPageID(_PageID);
}
}
WORK AROUND
I found a work around by wrapping my users control in a panel and hide/show panel if i have photos for that page or not. This is working fine but i still want to fix problem i have or even a better way of doing it.
<asp:Panel ID="pnl_uc_Gallery" runat="server" Visible="false">
// I have PUT all the USER CONTROL CODE In SIDE THIS BLOAK
</asp:Panel>
if (ds.Tables[0].Rows.Count > 0)
{
// showGallery(true);
pnl_uc_Gallery.Visible = true;
}
else
{
//showGallery(false);
pnl_uc_Gallery.Visible = false;
}
This code:
ucPhotoGallery.showGallery += delegate(bool showControl)
{
bool bShowControl = showControl;
ucPhotoGallery.Visible = bShowControl;
};
is in a !Page.IsPostback call; move it outside so that you are attaching to the event on every postback, not just the first one, or use a method as the event handler and set the method name in the markup. Either way, the issue is the event handler is established only on the first page load, not subsequent loads, and it needs to be done every time a request hits the server.

ListBox SelectedIndex always -1 in slectedindexchanged event handler

In the sample code there are two listboxes. In ListBox1 the items are defined in Default.aspx. In ListBox2 they are defined in the codefile. ListBox1 behaves as expected, the text box is updated whenever an item is selected. When ListBox2 triggers an event the selectedindex is always -1.
Default.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ListBox ID="ListBox1" runat="server" OnSelectedIndexChanged="lb1_OnSelectedIndexChanged" AutoPostBack="true">
<asp:ListItem>a</asp:ListItem>
<asp:ListItem>b</asp:ListItem>
</asp:ListBox>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:ListBox ID="ListBox2" runat="server" OnSelectedIndexChanged="lb1_OnSelectedIndexChanged" AutoPostBack="true">
</asp:ListBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</div>
</form>
</body>
</html>
Default.aspx.cs:
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<string> ab = new List<string>();
ab.Add("a");
ab.Add("b");
ListBox2.DataSource = ab;
ListBox2.DataBind();
ListBox1.SelectedIndexChanged += new EventHandler(lb1_OnSelectedIndexChanged);
ListBox2.SelectedIndexChanged += new EventHandler(lb2_OnSelectedIndexChanged);
}
protected void lb1_OnSelectedIndexChanged(object sender, EventArgs e)
{
if (ListBox1.SelectedIndex != -1)
{
TextBox1.Text = ListBox1.SelectedItem.Text;
}
}
protected void lb2_OnSelectedIndexChanged(object sender, EventArgs e)
{
if (ListBox2.SelectedIndex != -1)
{
TextBox2.Text = ListBox2.SelectedItem.Text;
}
}
}
The list of items has been moved to Default.aspx to get it working, but I'd really like to know what I'm doing wrong with this. -- Thanks!
You can't databind ListBox2 on every page load. Try:
Page_Load()...
{
if(!IsPostBack)
{
//databind listbox2
}
}
Try reading up a bit on the ASP.NET page lifecycle. On the postback, the ListBox2 will have it's correct state due to viewstate.
Your current code resets it. Hence the -1.

Trigger for UpdatePanel disappearing when added to a "custom control"

Basically, in a nutshell, the problem is that dynamically generated triggers for an UpdatePanel can no longer be found (by ASP.NET) as soon as I add them as children of a custom control.
Since the amount of code I'm working on is quite substantial I've recreated the problem on a smaller scale, which will make it easier to debug.
The error thrown in my face is:
A control with ID 'theTrigger' could not be found for the trigger in UpdatePanel 'updatePanel'.
I'm not sure whether this implementation of a "custom control" is the right way to go about it, but I did not write the original implementation: I'm working with code written by a previous developer to which I cannot make large modifications. It looks a little unusual to me, but, alas, this is what I've been given.
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestWeb.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:Panel runat="server" ID="panel">
</asp:Panel>
<asp:ScriptManager ID="scriptManager" runat="server"></asp:ScriptManager>
<asp:UpdatePanel runat="server" ID="updatePanel" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lblSomething" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace TestWeb
{
public partial class Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
UselessTableWrapper table = new UselessTableWrapper();
TableRow tr = new TableRow();
TableCell td = new TableCell();
LinkButton button1 = new LinkButton { ID = "theTrigger", Text = "Click Me" };
button1.Click += button1_Click;
td.Controls.Add(button1);
tr.Controls.Add(td);
table.AddRow(tr);
panel.Controls.Add(table);
// ### uncomment these lines (and comment the one above) to see it working
// ### without the custom control
/*
Table realTable = new Table();
realTable.Controls.Add(tr);
panel.Controls.Add(realTable);
*/
updatePanel.Triggers.Add(new AsyncPostBackTrigger { ControlID = "theTrigger", EventName = "Click" });
scriptManager.RegisterAsyncPostBackControl(button1);
}
protected void button1_Click(object sender, EventArgs e)
{
lblSomething.Text = "Random number: " + new Random().Next(100);
updatePanel.Update();
}
}
}
MyControl.cs
using System;
using System.Web.UI.WebControls;
namespace TestWeb
{
public class UselessTableWrapper : WebControl
{
private Table table = new Table();
protected override void OnPreRender(EventArgs e)
{
Controls.Add(table);
}
public void AddRow(TableRow row)
{
table.Controls.Add(row);
}
}
}
Any ideas would be greatly appreciated.
Edit
I've tried switching the OnPreRender event for this (found in a tutorial):
protected override void RenderContents(HtmlTextWriter writer)
{
writer.BeginRender();
table.RenderControl(writer);
writer.EndRender();
base.RenderContents(writer);
}
... hoping that it would fix it, but it does not.
this is the approach that I've taken with loading a ascx web control inside an aspx control from the code behind.
In the control:
namespace dk_admin_site.Calculations
{
public partial class AssignedFieldCalculation : System.Web.UI.UserControl
{
public static AssignedFieldCalculation LoadControl(Calculation initialData)
{
var myControl = (AssignedFieldCalculation) ((Page) HttpContext.Current.Handler).LoadControl(#"~\\Calculations\AssignedFieldCalculation.ascx");
myControl._initialData = initialData;
return myControl;
}
private Calculation _initialData;
public Calculation Data { get { return _initialData; } }
protected void Page_Load(object sender, EventArgs e) {}
}
}
in the web form code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
{
if (ScriptManager1.AsyncPostBackSourceElementID.StartsWith("ctl00$MainContent$calc") && ScriptManager1.AsyncPostBackSourceElementID.EndsWith("$btnRemoveCalculationFromField"))
{
//do something on the postback
}
else if (ScriptManager1.AsyncPostBackSourceElementID.StartsWith("ctl00$MainContent$calc") && (ScriptManager1.AsyncPostBackSourceElementID.EndsWith("$btnMoveCalculationUp") || ScriptManager1.AsyncPostBackSourceElementID.EndsWith("$btnMoveCalculationDown")))
{
//do something on the postback
}
}
foreach (Calculation calc in calculationCollection)
{
AssignedFieldCalculation asCalc = AssignedFieldCalculation.LoadControl(calc);
asCalc.ID = "calc" + calc.UniqueXKey;
pnlFieldCalculations.Controls.Add(asCalc);
foreach (Control ct in asCalc.Controls)
{
if (ct.ID == "btnMoveCalculationDown" || ct.ID == "btnMoveCalculationUp" || ct.ID == "btnRemoveCalculationFromField")
{
ScriptManager1.RegisterAsyncPostBackControl(ct);
}
}
}
}
A few things to note:
You need to make each control ID unique when adding it to the asp:Panel (called pnlFieldCalculations).
The LoadControl method allows you to pass initial arguments

Categories

Resources