ASP.NET C# - How do I set a public property for a CheckBoxList inside a UserControl?
I'm having trouble figuring this out. If I have a checkboxlist inside a usercontrol, how开发者_JAVA百科 do I loop through (or check, really) what boxes are checked in the list?
As I said in the comment below, I'd like to expose the checked items through a property in the control itself.
From your page you can do
var checkboxes = (CheckBoxList)userControl1.FindControl("checkBoxList1");
But a better solution in my mind would be to expose the checked items through a property or method.
In user control
public string[] CheckedItems {
get {
List<string> checkedItems = new List<string>();
foreach (ListItem item in checkbox1.Items)
checkedItems.Add(item.Value);
return checkedItems.ToArray();
}
}
Then in the page
var checkedItems = userControl1.CheckedItems;
You could also just return checkbox1.Items
in the property, but that isn't good encapsulation.
If you are using .net 3.5, you can create a readonly property that uses LINQ to return an IList of just the selected values:
public IList<string> SelectedItems{
get {
return checkbox1.Items.Cast<ListItem>.Where(i => i.Selected).Select(j => j.Value).ToList();
}
}
精彩评论