我有一个带有1 2 3 ... 40项目的组合框,如果我选择了值4,那么我应该可以在列表框中添加的值不超过4个值。这就是我在想的但没有用。
public Form1()
{
InitializeComponent();
}
private void add_Click(object sender, EventArgs e)
{
int allowedItemsCount = 0;
Int32.TryParse(comboBox1.SelectedText, out allowedItemsCount);
int currentItemsCount = listBox1.Items.Count;
if (currentItemsCount < allowedItemsCount)
{
listBox1.Items.Add(textBox1.Text);
}
}
private void delete_Click(object sender, EventArgs e)
{
if (listBox1.SelectedItems.Count != 0)
{
while (listBox1.SelectedIndex != -1)
{
listBox1.Items.RemoveAt(listBox1.SelectedIndex);
}
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int x = 0;
Int32.TryParse(comboBox1.SelectedText, out x);
int count = listBox1.Items.Count;
if (count > x)
{
listBox1.Items.Clear();
int difference = count - x;
for (int i = 0; i < difference; i++)
{
listBox1.Items.RemoveAt(listBox1.Items.Count - 1);
}
}
}
}
这是您要求的完整代码,但无法使用...现在,添加按钮不起作用。
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int x = 0;
Int32.TryParse(comboBox1.SelectedText, out x);
int count = listBox1.Items.Count;
if (count > x)
{
listBox1.Items.Clear();
int difference = count - x;
for(int i = 0 ; i < difference ; i++)
{
listBox1.Items.RemoveAt(listBox1.Items.Count-1);
}
}
}
更新
根据您的评论,在您的添加按钮单击事件中编写此代码
int allowedItemsCount = 0;
Int32.TryParse(comboBox1.SelectedText, out allowedItemsCount);
int currentItemsCount = listBox1.Items.Count;
if(currentItemsCount < allowedItemsCount)
{
listBox1.Items.Add(textBox1.Text); // I assume your textbox id is TextBox1
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句