覆盖ListBox控件返回一个连接字符串值 [英] Override the Listbox Control to return a concatenated string value
本文介绍了覆盖ListBox控件返回一个连接字符串值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要重新定义ListBox类,以确保它返回所有选定项目的CSV字符串,也应采取以CSV字符串,并在需要时填充列表框。可以说我有这个code。什么是我要重写?我该怎么办的职能?
使用系统;
使用System.Web.UI.WebControls;
使用System.ComponentModel;
命名空间MY.WebControl
{
公共类ListBoxString:列表框
{ }
}
解决方案
如果你想要做的就是添加的功能,您还可以添加扩展方法来添加此功能。这里有两个简单的例子是GetSelectItems到CSV字符串,并AddListItems从字符串数组。
公共静态字符串GetSelectedItems(这个列表框lbox)
{
清单<串GT; selectedValues =新的List<串GT;(); INT [] = selectedIndeces lbox.GetSelectedIndices(); 的foreach(INT我在selectedIndeces)
selectedValues.Add(lbox.Items [I]。价值); 返回的string.join(,,selectedValues.ToArray());
} 公共静态无效SetSelectedItems(这个列表框lbox,字符串[]值)
{
的foreach(在值字符串值)
{
lbox.Items [lbox.Items.IndexOf(lbox.Items.FindByValue(值))]选择= TRUE。
}
} 公共静态无效AddListItems(这个列表框lbox,字符串[]值)
{
的foreach(在值字符串值)
{
列表项项=新的ListItem(值);
lbox.Items.Add(项目);
}
}
I have to redefine the ListBox class to make sure that it returns a csv string of all the selected items and also should take in a csv string and populate the listbox when needed. Lets say I have this code. What are the functions that I have to override and how do I do it?
using System;
using System.Web.UI.WebControls;
using System.ComponentModel;
namespace MY.WebControl
{
public class ListBoxString : ListBox
{
}
}
解决方案
If all you want to do is add functionality, you can also add Extension Methods to add this capability. Here are 2 quick examples that GetSelectItems to a CSV string and AddListItems from a string array.
public static string GetSelectedItems(this ListBox lbox)
{
List<string> selectedValues = new List<string>();
int[] selectedIndeces = lbox.GetSelectedIndices();
foreach (int i in selectedIndeces)
selectedValues.Add(lbox.Items[i].Value);
return String.Join(",",selectedValues.ToArray());
}
public static void SetSelectedItems(this ListBox lbox, string[] values)
{
foreach (string value in values)
{
lbox.Items[lbox.Items.IndexOf(lbox.Items.FindByValue(value))].Selected = true;
}
}
public static void AddListItems(this ListBox lbox, string[] values)
{
foreach (string value in values)
{
ListItem item = new ListItem(value);
lbox.Items.Add(item);
}
}
这篇关于覆盖ListBox控件返回一个连接字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文