如何限制列表框中值(条目)的最大数量
本文关键字:条目 最大数 何限制 列表 | 更新日期: 2023-09-27 18:05:52
我目前有两个listbox (ListBox1和ListBox2),在ListBox1中有12个静态值(value1, value2, value3等),允许用户使用添加和删除按钮在它们之间传输值。我还有一个下拉框。我如何在ListBox2上强制一个max当一个特定的选择是在那个下拉框?换句话说,当在下拉框中选择一个值时,如果我只想允许从Listbox1中最多移动一个条目到Listbox2。
protected void MoveRight(object sender, EventArgs e)
{
while (ListBox1.Items.Count > 0 && ListBox1.SelectedItem != null)
{
ListItem selectedItem = ListBox1.SelectedItem;
selectedItem.Selected = false;
ListBox2.Items.Add(selectedItem);
ListBox1.Items.Remove(selectedItem);
}
}
protected void MoveLeft(object sender, EventArgs e)
{
while (ListBox2.Items.Count > 0 && ListBox2.SelectedItem != null)
{
ListItem selectedItem = ListBox2.SelectedItem;
selectedItem.Selected = false;
ListBox1.Items.Add(selectedItem);
ListBox2.Items.Remove(selectedItem);
}
}
private void BindData()
{
ListBox1.Items.Add(new ListItem("01", "01"));
ListBox1.Items.Add(new ListItem("02", "02"));
ListBox1.Items.Add(new ListItem("03", "03"));
ListBox1.Items.Add(new ListItem("04", "04"));
ListBox1.Items.Add(new ListItem("05", "05"));
ListBox1.Items.Add(new ListItem("06", "06"));
ListBox1.Items.Add(new ListItem("07", "07"));
ListBox1.Items.Add(new ListItem("08", "08"));
ListBox1.Items.Add(new ListItem("09", "09"));
ListBox1.Items.Add(new ListItem("10", "10"));
ListBox1.Items.Add(new ListItem("11", "11"));
ListBox1.Items.Add(new ListItem("12", "12"));
}
使用for循环,迭代最大值和列表项数中的小数。
protected void MoveRight(object sender, EventArgs e)
{
int max = 1;
int iterations = ListBox1.Items.Count < max ? ListBox1.Items.Count : max
for(int i = 0; i < iterations; i++)
{
ListItem selectedItem = ListBox1.SelectedItem;
if(selectedItem == null)
break;
selectedItem.Selected = false;
ListBox2.Items.Add(selectedItem);
ListBox1.Items.Remove(selectedItem);
}
}
现在您可以将max
移动到类定义中,并根据需要对其进行操作。
你可以试试下面的代码
int YourMax = 10;
if(ListBox1.Items.Count < Yourmax)
{
//Add item
}
链接:http://msdn.microsoft.com/fr-fr/library/system.windows.forms.listbox.objectcollection_members(v=vs.80).aspx
注意:你没有这个需要的属性
这里的所有属性:http://msdn.microsoft.com/fr-fr/library/aeb9t2b5(v=vs.80).aspx
您希望如何在代码隐藏中处理它?如果您希望在下拉列表设置为1时最多复制一个选定项,您可以这样做:
protected void MoveRight(object sender, EventArgs e)
{
int max = Convert.ToInt32(DropDownList1.SelectedValue);
for(int i=0;i<max && ListBox1.Items.Count > 0 && ListBox1.SelectedItem != null; i++)
{
ListItem selectedItem = ListBox1.SelectedItem;
selectedItem.Selected = false;
ListBox2.Items.Add(selectedItem);
ListBox1.Items.Remove(selectedItem);
}
}
或者,如果您希望ListBox1
中选择了2个项目,而下拉列表设置为1的情况是验证错误,您可以为CustomValidator
的ServerValidate
事件编写处理程序:
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs e)
{
// There's probably a simpler way to get a count of items selected
e.IsValid = ListBox1.Items.Count(li=> li.Selected) <= Convert.ToInt32(DropDownList1.SelectedValue);
}
或者,如果您希望在客户端发生这种情况,则必须编写一些javascript。