Page cannot be null error custom MOSS 2007 Webpart - asp.net

I'm trying to write a webpart that basically pulls data from a list and displays it to the user. There is a feature news list where one of the columns holds a URL to an image. The web part should get the 3 most recent feature news items and create three image controls on the page. These image controls can be scrolled through by clicking on the buttons 1,2,3. (Ie, clicking on 2 will set the Visible property of image 1 and image 3 to false).
I have managed to implement AJAX here, but am now trying to use the UpdatePanelAnimationExtender from the AJAX Control Toolkit.
I have followed all instructions on how to use the toolkit, add it to the GAC, add a safe assembly, etc, and have gotten past all the errors besides this one:
"Page cannot be null. Please ensure that this operation is being performed in the context of an ASP.NET request"
My complete code below:
using System; using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.WebControls;
using System.Web.Extensions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using System.ComponentModel;
using AjaxControlToolkit;
namespace FeatureNewsWebpartFeature {
[Guid("7ad4b959-d494-4e85-b164-4e4231692b8b")]
public class FeatureNewsWebPart : Microsoft.SharePoint.WebPartPages.WebPart
{
private bool _error = false;
private string _listName = null;
private string _imageColumn = null;
Image image1;
Image image2;
Image image3;
UpdatePanelAnimationExtender upAnimator;
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.Category("List Connection Settings")]
[WebDisplayName("List Name")]
[WebDescription("Enter the name of the news list")]
public string ListName
{
get
{
if (_listName == null)
{
_listName = "News";
}
return _listName;
}
set { _listName = value; }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.Category("List Connection Settings")]
[WebDisplayName("Image Column Name")]
[WebDescription("Enter the column name of the ArtfulBits Image Upload column")]
public string ImageUrlColumn
{
get
{
if (_imageColumn == null)
{
_imageColumn = "Feature Image";
}
return _imageColumn;
}
set { _imageColumn = value; }
}
public FeatureNewsWebPart()
{
this.ExportMode = WebPartExportMode.All;
}
/// <summary>
/// Create all your controls here for rendering.
/// Try to avoid using the RenderWebPart() method.
/// </summary>
protected override void CreateChildControls()
{
if (!_error)
{
try
{
base.CreateChildControls();
//Create script manager
if (ToolkitScriptManager.GetCurrent(this.Page) == null)
{
ToolkitScriptManager scriptHandler = new ToolkitScriptManager();
scriptHandler.ID = "scriptHandler";
scriptHandler.EnablePartialRendering = true;
this.Controls.Add(scriptHandler);
}
//Create update panel
System.Web.UI.UpdatePanel imageUpdatePanel = new System.Web.UI.UpdatePanel();
imageUpdatePanel.ID = "imageUpdatePanel";
imageUpdatePanel.UpdateMode = UpdatePanelUpdateMode.Conditional;
this.Controls.Add(new LiteralControl("<div id=\"updateContainer\">"));
this.Controls.Add(imageUpdatePanel);
this.Controls.Add(new LiteralControl("</div>"));
//Make SPSite object and retrieve the three most recent feature news items
SPSite site = SPContext.Current.Site;
using (SPWeb web = site.OpenWeb())
{
SPList oList = web.Lists[ListName];
SPQuery oQuery = new SPQuery();
oQuery.RowLimit = 3;
oQuery.Query = "<OrderBy>" +
"<FieldRef Name='Modified' Ascending='False' /></OrderBy>" +
"<Where>" +
"<Eq>" +
"<FieldRef Name='ContentType' />" +
"<Value Type='Choice'>Feature News Item</Value>" +
"</Eq>" +
"</Where>";
oQuery.ViewFields = string.Concat(
"<FieldRef Name='Feature_x0020_Image' />" +
"<FieldRef Name='Feature_x0020_Order' />");
image1 = new Image();
image2 = new Image();
image3 = new Image();
//For each item, extract image URL and assign to image object
SPListItemCollection items = oList.GetItems(oQuery);
foreach (SPListItem oListItem in items)
{
string url = oListItem["Feature_x0020_Image"].ToString();
url = url.Substring(url.IndexOf("/Lists"));
url = url.Remove(url.IndexOf(";#"));
switch (oListItem["Feature_x0020_Order"].ToString())
{
case "1":
image1.ImageUrl = url;
break;
case "2":
image2.ImageUrl = url;
break;
case "3":
image3.ImageUrl = url;
break;
default:
//ERROR
break;
}
}
if (!(Page.IsPostBack))
{
image1.Visible = true;
image2.Visible = false;
image3.Visible = false;
}
imageUpdatePanel.ContentTemplateContainer.Controls.Add(image1);
imageUpdatePanel.ContentTemplateContainer.Controls.Add(image2);
imageUpdatePanel.ContentTemplateContainer.Controls.Add(image3);
//Create animation for update panel
upAnimator = new UpdatePanelAnimationExtender();
upAnimator.ID = "upAnimator";
upAnimator.TargetControlID = imageUpdatePanel.ID;
const string xml = "<OnUpdating>" +
"<Parallel duration=\".25\" Fps=\"30\">" +
"<FadeOut AnimationTarget=\"updateContainer\" minimumOpacity=\".2\" />" +
"</OnUpdating>" +
"<OnUpdated>" +
"<FadeIn AnimationTarget=\"updateContainer\" minimumOpacity=\".2\" />" +
"</OnUpdated>";
Animation.Parse(xml, upAnimator);
this.Controls.Add(upAnimator);
Button b1 = new Button();
b1.ID = "b1i";
b1.Click += new EventHandler(b1_Click);
b1.Text = "Image 1";
Button b2 = new Button();
b2.ID = "b2i";
b2.Click += new EventHandler(b2_Click);
b2.Text = "Image 2";
Button b3 = new Button();
b3.ID = "b3i";
b3.Click += new EventHandler(b3_Click);
b3.Text = "Image 3";
this.Controls.Add(b1);
this.Controls.Add(b2);
this.Controls.Add(b3);
AsyncPostBackTrigger tr1 = new AsyncPostBackTrigger();
tr1.ControlID = b1.ID;
//tr1.EventName = "Click";
imageUpdatePanel.Triggers.Add(tr1);
AsyncPostBackTrigger tr2 = new AsyncPostBackTrigger();
tr2.ControlID = b2.ID;
//tr2.EventName = "Click";
imageUpdatePanel.Triggers.Add(tr2);
AsyncPostBackTrigger tr3 = new AsyncPostBackTrigger();
tr3.ControlID = b3.ID;
//tr3.EventName = "Click";
imageUpdatePanel.Triggers.Add(tr3);
}
}
catch (Exception ex)
{
HandleException(ex);
}
}
}
void b1_Click(object sender, EventArgs e)
{
image1.Visible = true;
image2.Visible = false;
image3.Visible = false;
}
void b2_Click(object sender, EventArgs e)
{
image1.Visible = false;
image2.Visible = true;
image3.Visible = false;
}
void b3_Click(object sender, EventArgs e)
{
image1.Visible = false;
image2.Visible = false;
image3.Visible = true;
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
}
protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
}
/// <summary>
/// Ensures that the CreateChildControls() is called before events.
/// Use CreateChildControls() to create your controls.
/// </summary>
/// <param name="e"></param>
protected override void OnLoad(EventArgs e)
{
if (!_error)
{
try
{
base.OnLoad(e);
this.EnsureChildControls();
// Your code here...
}
catch (Exception ex)
{
HandleException(ex);
}
}
}
/// <summary>
/// Clear all child controls and add an error message for display.
/// </summary>
/// <param name="ex"></param>
private void HandleException(Exception ex)
{
this._error = true;
this.Controls.Clear();
this.Controls.Add(new LiteralControl(ex.Message));
}
} }

Here's a related question though being asked in the context of SP 2010, it's still directly applicable given the solution.
We have a CQWP on our MOSS farm that does essentially the same thing: reads items from a list using jQuery and the SPServices plugin and animates slider changes. The most difficult part of the process is actually tweaking the look, if I remember correctly. Once you have the right pieces, putting it together is a snap.

Related

How to categorize product by it's types in Asp.net using Webforms

I want to sort the products by their type, using dropdownlist.
products by types isn't working when i select it in dropdown list.
stored procedure of ProductByType:
Public List<Product> GetProductsByType(int typeId)
{
try
{
using (GarageDBEntities db = new GarageDBEntities())
{
//select * from table where condition is required type
List<Product> products = (from x in db.Products
where x.TypeId == typeId
select x).ToList();
return products;
}
}
catch (Exception)
{
return null;
}
}
Index page code to display products:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
FillPage();
}
private void FillPage()
{
//Get a lsit of all products in DB
ProductModel productModel = new ProductModel();
List<Product> products = productModel.GetAllProducts();
//Make sure products exists in the database
if (products != null)
{
//Create a new Panel with an ImageButton and 2 labels for each Product
foreach (Product product in products)
{
Panel productPanel = new Panel();
ImageButton imageButton = new ImageButton();
Label lblName = new Label();
Label lblPrice = new Label();
//Set childControls properties
imageButton.ImageUrl = "~/Images/Products/" + product.Image;
imageButton.CssClass = "productImage";
imageButton.PostBackUrl = "~/Pages/Product.aspx?id=" + product.Id;
lblName.Text = product.Name;
lblName.CssClass = "productName";
lblPrice.Text = "₹" + product.Price;
lblPrice.CssClass = "productPrice";
//Add child controls to Panel
productPanel.Controls.Add(imageButton);
productPanel.Controls.Add(new Literal { Text = "<br />" });
productPanel.Controls.Add(lblName);
productPanel.Controls.Add(new Literal { Text = "<br />" });
productPanel.Controls.Add(lblPrice);
//Add dynamic Panels to static Parent panel
pnlProducts.Controls.Add(productPanel);
}
}
else
{
//No products found
pnlProducts.Controls.Add(new Literal { Text = "No Products Found!" });
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
ProductModel productModel = new ProductModel();
List<Product> products = productModel.GetProductsByType(Convert.ToInt32(DropDownList1.SelectedItem.Value));
foreach (Product product in products)
{
Panel productPanel = new Panel();
ImageButton imageButton = new ImageButton();
Label lblName = new Label();
Label lblPrice = new Label();
//Set childControls properties
imageButton.ImageUrl = "~/Images/Products/" + product.Image;
imageButton.CssClass = "productImage";
imageButton.PostBackUrl = "~/Pages/Product.aspx?id=" + product.Id;
lblName.Text = product.Name;
lblName.CssClass = "productName";
lblPrice.Text = "₹" + product.Price;
lblPrice.CssClass = "productPrice";
//Add child controls to Panel
productPanel.Controls.Add(imageButton);
productPanel.Controls.Add(new Literal { Text = "<br />" });
productPanel.Controls.Add(lblName);
productPanel.Controls.Add(new Literal { Text = "<br />" });
productPanel.Controls.Add(lblPrice);
//Add dynamic Panels to static Parent panel
pnlProducts.Controls.Add(productPanel);
}
}
}
It always showing all the products even tho when I select product type.
As shown in image, I selected "Engine Oil" but it showing all the products.
I want it to show particular products only of the selected product type chosen in dropdownlist.
Try add the PostBack validation in your Page_Load event:
C# Code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillPage();
}
}
Most likely, when selecting an item in the dropdownlist, a postback is generated which will call PageLoad and reload all the products, to avoid this the PostBack validation is usually set
Make sure to use the AutoPostBack="True" flag in the <asp:DropDownList /> control

drop-down list in C# issue

drop-down list in C#.net not showing the items it supposed to show!
i hv a drop-down list that suppose to show image names from a folder, but it is not doing that!
i dont have errors when launching the .aspx file!
buuuuuut when i get output there is only empty dropdown list!
this the ManageProducts.aspx codes are:
Name:
Type:
" SelectCommand="SELECT * FROM [ProductTypes] ORDER BY [Name]">
Price:
Image:
Description:
and this the behind codes:
using System;
using System.Collections;
using System.IO;
public partial class PagesNew_ManagementPages_ManageProducts : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack) //this baby makes the data not come every time the pg is refreshed ,
//postback=refresh page
GetImages();
}
private void GetImages()
{
try
{
//get all filepaths
string[] images = Directory.GetFiles(Server.MapPath("~/Img/Products/"));
//get all filenames and put them in a stupid array....yeah DSA days
ArrayList imageList = new ArrayList();
foreach (string image in images)
{
string imageName = image.Substring(image.LastIndexOf(#"\", StringComparison.Ordinal) + 1);
imageList.Add(imageName);
// see the Array in dd viwe datasource and refresh
ddImage.AppendDataBoundItems = true;
ddImage.DataBind();
}
}
catch (Exception e)
{
lblResult.Text = e.ToString();
}
}
protected void ddImage_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
You want to bind your datalist outside of the for loop.
ArrayList imageList = new ArrayList();
foreach (string image in images)
{
string imageName = image.Substring(image.LastIndexOf(#"\", StringComparison.Ordinal) + 1);
imageList.Add(imageName);
}
ddImage.DataSource = imageList;
ddImage.AppendDataBoundItems = true;
ddImage.DataBind();

Can't use Control.FindControl on dynamically created System.Web.UI.WebControl

Why would the following code not work? I am creating a control, adding a child control and attempting to retrieve it by id using the .FindControl method.
[Test]
public void TryToFindControl()
{
var myPanel = new Panel();
var textField = new TextBox
{
ID = "mycontrol"
};
myPanel.Controls.Add(textField);
var foundControl = myPanel.FindControl("mycontrol");
// this fails
Assert.IsNotNull(foundControl);
}
Panel has not been added to Page yet, so you cannot use FindControl. Instead, you need to find it inside Panel.Controls
[TestMethod]
public void TryToFindControl()
{
var myPanel = new Panel();
var textField = new TextBox
{
ID = "mycontrol"
};
myPanel.Controls.Add(textField);
var foundControl = myPanel.Controls
.OfType<TextBox>()
.FirstOrDefault(x => x.ID == "mycontrol");
Assert.IsNotNull(foundControl);
}
Testing with Page
FindControl works only if container is added to Page.
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var myPanel = new Panel();
var textField = new TextBox
{
ID = "mycontrol"
};
myPanel.Controls.Add(textField);
Controls.Add(myPanel);
// foundControl is not null anymore!
var foundControl = myPanel.FindControl("mycontrol");
}
}
The control must be part of the server side Page control collection hierarchy to be found.
public void TryToFindControl()
{
var myPanel = new Panel();
// key line here
Page.Controls.Add(myPanel);
var textField = new TextBox
{
ID = "mycontrol"
};
myPanel.Controls.Add(textField);
var foundControl = myPanel.FindControl("mycontrol");
Assert.IsNotNull(foundControl);
}
First I'll start form the fact I don't know of System.UI.Control, Rather System.Web.UI.Control
Then I could not find TextField Control so I used Web TextBox instead. Please adjust your code as necessary. I also used VS Test attributes
[TestMethod()]
public void TryToFindControl()
{
var editContainer = new HtmlTableCell();
editContainer.Controls.Add(new TextBox
{
ID = "mycontrol",
});
System.Web.UI.Control foundControl = null;
foreach (System.Web.UI.Control ctrl in editContainer.Controls)
{
if (ctrl.ID == "mycontrol")
{
foundControl = ctrl;
break;
}
}
// This works
Assert.IsNotNull(foundControl);
}
Based on your exact wording, if you want to access the control you added, create an instance first as variable, so you can access it directly. Please keep in mind that I don't know what you are trying to achieve globally, so my answer(s) may not apply because of that, or there maybe be better solution.
[TestMethod()]
public void TryToFindControl()
{
var editContainer = new HtmlTableCell();
var foundControl = new TextBox
{
ID = "mycontrol"
};
editContainer.Controls.Add(foundControl);
// This works
Assert.IsNotNull(foundControl);
}

Adding a new item in database through combobox

I am having a database and I use it through Entity Framework, I need to update the data by editing the other items in text boxes and grid, that is working fine and below is the code:
In aspx.cs
protected void SaveBtn_Click(object sender, EventArgs e)
{
obj.Address = AppAddress.Text;
obj.City = AppCity.Text;
obj.Email = AppEmail.Text;
obj.Notes = AppComments.Text;
obj.Postal = AppPostal.Text;
obj.AppraiserAppraiserCompanyId = ApprCompCmbx.SelectedIndex;
obj.ProvinceState = Province.SelectedIndex;
apprblobj.GetUpdate(obj);
Response.Write("<script>alert('You have successfully updated the Data');</script>");
}
call in the BL:
public void GetUpdate(Appraiser appObj)
{
obj.UpdateData(appObj);
}
and in the DAL
public void UpdateData(Appraiser apprObj)
{
try
{
var Appsave = context.Appraisers.FirstOrDefault(App => App.AppraiserId == apprObj.AppraiserId);
if (Appsave != null)
{
Appsave.AppraiserName = apprObj.AppraiserName;
Appsave.AppraiserAppraiserCompanyId = apprObj.AppraiserAppraiserCompanyId;
Appsave.Address = apprObj.Address;
Appsave.City = apprObj.City;
Appsave.ProvinceState = apprObj.ProvinceState;
Appsave.Email = apprObj.Email;
Appsave.Postal = apprObj.Postal;
Appsave.Notes = apprObj.Notes;
context.SaveChanges();
}
}
catch (Exception ex)
{
log.Debug("Appraiser : UpdateData: " + ex.Message + " Trace : " + ex.StackTrace);
}
}
Now I wanto to add a new item through the same combobox and on the button click functionality as it is doing all the work like add, update and delete.
Kindly provide me the hint: This I know that addobject(__) will ve used in place of savechanges etc.

ASP.NET Server Control based on RadComboBox - Postback issue

I am trying to create a custom control that extends the RadComboBox from Telerik to create a Dropdown Checkbox List with default templates. The plan is to use the control in several places so I wanted to consolidate all of the logic in one spot.
However I am experiencing a couple of weird issues on postback. If you check a couple of items and then hit the Apply button the correct items are selected, but the text on the checkbox is different. Then on the next postback I get the error Multiple controls with the same ID 'i2' were found. FindControl requires that controls have unique IDs.
Attached is the custom control. Any help is appreciated.
C# Code:
/// <summary>
/// Private Header template class for the DropdownCheckboxList
/// </summary>
class CheckboxListFooterTemplate : ITemplate
{
#region Public Methods
public void InstantiateIn(Control container)
{
string footer = "<input type=\"submit\" value=\"Apply\" />";
container.Controls.Add(new LiteralControl(footer));
}
#endregion Public Methods
}
/// <summary>
/// Private Header template class for the DropdownCheckboxList
/// </summary>
class CheckboxListHeaderTemplate : ITemplate
{
#region Public Methods
public void InstantiateIn(Control container)
{
string header = "<input type=\"button\" value=\"Check All\" onclick=\"CheckAll("{0}", true)\" />";
header += " <input type=\"button\" value=\"Uncheck All\" onclick=\"CheckAll("{0}", false)\" />";
container.Controls.Add(new LiteralControl(string.Format(header, container.Parent.ClientID)));
}
#endregion Public Methods
}
/// <summary>
/// Template class for the DropdownChecklistBox
/// </summary>
class CheckboxListTemplate : ITemplate
{
#region Constants
//this div will stop the list from closing as a listitem is clicked
const string head = "<div onclick=\"StopPropagation(event)\" class=\"combo-item-template\">";
const string tail = "</div>";
#endregion Constants
#region Private Methods
/// <summary>
/// Bind the data to the checkbox
/// </summary>
/// <param name="sender">Checkbox to bind data to</param>
/// <param name="e"></param>
private void checkbox_DataBinding(object sender, EventArgs e)
{
CheckBox target = (CheckBox)sender;
RadComboBoxItem item = (RadComboBoxItem)target.BindingContainer;
string itemText = (string)DataBinder.Eval(item, "Text");
target.Text = itemText;
}
#endregion Private Methods
#region Public Methods
/// <summary>
/// Create the checkbox list items in the template
/// </summary>
/// <param name="container">Container that the control will be added</param>
public void InstantiateIn(Control container)
{
CheckBox checkbox = new CheckBox();
checkbox.ID = "chkList";
checkbox.Attributes.Add("onclick", string.Format("onCheckBoxClick(this, \"{0}\")", container.Parent.ClientID));
container.Controls.Add(new LiteralControl(head));
checkbox.DataBinding += new EventHandler(checkbox_DataBinding);
container.Controls.Add(checkbox);
container.Controls.Add(new LiteralControl(tail));
}
#endregion Public Methods
}
//todo: complete summary
/// <summary>
/// based on telerik demo: http://demos.telerik.com/aspnet-ajax/combobox/examples/functionality/templates/defaultcs.aspx
/// </summary>
[DefaultProperty("Text")]
[ToolboxData("<{0}:DropdownCheckboxList runat=server></{0}:DropdownCheckboxList>")]
public class DropdownCheckboxList : RadComboBox, INamingContainer
{
#region Private Properties
string SelectedText
{
get
{
StringBuilder values = new StringBuilder(SelectedItems.Count);
foreach (RadComboBoxItem item in SelectedItems)
values.Append(item.Text + ", ");
if (values.Length > 0)
return values.ToString().Remove(values.Length - 2, 2);
else
return EmptyMessage;
}
}
#endregion Private Properties
#region Public Properties
public RadComboBoxItemCollection SelectedItems
{
get
{
CheckBox chk = null;
RadComboBoxItemCollection selectedItems = new RadComboBoxItemCollection(this);
foreach (RadComboBoxItem item in Items)
{
chk = (CheckBox)item.FindControl("chkList");
if (chk != null && chk.Checked)
selectedItems.Add(item);
}
return selectedItems;
}
}
//todo: summary
public override string SelectedValue
{
get
{
StringBuilder values = new StringBuilder(SelectedItems.Count);
foreach (RadComboBoxItem item in SelectedItems)
values.Append(item.Value + ", ");
if (values.Length > 0)
return values.ToString().Remove(values.Length - 2, 2);
else
return "";
}
set
{
if (value != null)
SelectedValues = new List<string>(value.Split(','));
}
}
//todo: summary
public List<string> SelectedValues
{
get
{
List<string> selectedValues = new List<string>();
foreach (RadComboBoxItem item in SelectedItems)
{
selectedValues.Add(item.Value);
}
return selectedValues;
}
set
{
RadComboBoxItem item = null;
CheckBox chk = null;
foreach (string val in value)
{
item = Items.FindItemByValue(val.Trim());
if (item != null)
{
chk = (CheckBox)item.FindControl("chkList");
if (chk != null)
chk.Checked = true;
}
}
}
}
#endregion Public Properties
#region Protected Methods
protected override void CreateChildControls()
{
if (base.HeaderTemplate == null)
base.HeaderTemplate = new CheckboxListHeaderTemplate();
if (base.ItemTemplate == null)
base.ItemTemplate = new CheckboxListTemplate();
if (base.FooterTemplate == null)
base.FooterTemplate = new CheckboxListFooterTemplate();
base.CreateChildControls();
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
string resourceName = "CustomControls.DropdownCheckboxList.js";
ClientScriptManager cs = this.Page.ClientScript;
cs.RegisterClientScriptResource(typeof(CustomControls.DropdownCheckboxList), resourceName);
Text = SelectedText;
}
#endregion Protected Methods
}
Javascript Code:
//based on telerik demo: http://demos.telerik.com/aspnet-ajax/combobox/examples/functionality/templates/defaultcs.aspx
var cancelDropDownClosing = false;
function StopPropagation(e) {
//cancel bubbling
e.cancelBubble = true;
if (e.stopPropagation) {
e.stopPropagation();
}
}
function onDropDownClosing() {
cancelDropDownClosing = false;
}
function CheckAll(comboBoxId, value) {
var combo = $find(comboBoxId);
//get the collection of all items
var items = combo.get_items();
//enumerate all items
for (var i = 0; i < items.get_count(); i++) {
var item = items.getItem(i);
//get the checkbox element of the current item
var chk1 = $get(combo.get_id() + "_i" + i + "_chkList");
chk1.checked = value;
}
}
function onCheckBoxClick(chk, comboBoxId) {
var combo = $find(comboBoxId);
//holds the text of all checked items
var text = "";
//holds the values of all checked items
var values = "";
//get the collection of all items
var items = combo.get_items();
//enumerate all items
for (var i = 0; i < items.get_count(); i++) {
var item = items.getItem(i);
//get the checkbox element of the current item
var chk1 = $get(combo.get_id() + "_i" + i + "_chkList");
if (chk1.checked) {
text += item.get_text() + ", ";
values += item.get_value() + ", ";
}
}
//remove the last comma from the string
text = removeLastComma(text);
values = removeLastComma(values);
if (text.length > 0) {
//set the text of the combobox
combo.set_text(text);
}
else {
//all checkboxes are unchecked
//so reset the controls
combo.set_text("");
}
}
//this method removes the ending comma from a string
function removeLastComma(str) {
return str.replace(/,$/, "");
}
This line in InstantiateIn(Control container) is primary cause of the problem:
checkbox.ID = "chkList";
This line makes every checkbox have the same id - they should be unique.
So it might look more like this
checkbox.ID = Container.ID + SomeUniqueString;
I created a project with the code you provided and duplicated the error with only one control on the page. (there were other errors in the javascript also, but I was able to ignore those.)
I could see no easy way to create the unique ids so that you could know what they were to do the find. So instead of this:
chk = (CheckBox)item.FindControl("chkList");
I tried this:
foreach (var o in item.Controls)
{
if (o is CheckBox)
{
chk = (CheckBox) o;
}
}
It eliminated the error and allowed me to select more than one item. However, this code is not ideal - it makes the assumption that there is only one check box. You would be better off making sure the ids are unique. The approach I would take would be to base the id on the value of the combo box item.
If the selectable items are fixed (the user can't add new items through the combo box) you might try using a RadMenu instead. We have a very simialr control, but we use RadMenu. We simply set the image on the menu item to indicate selection status, and we keep track of selected items within our control.

Resources