[英]Adding sorted and unsorted integer to list box in C#
在我的系统中,我有一个文本框和按钮,允许用户向列表框输入一个整数。 但是,我想包括两个单选按钮-排序和未排序,以便用户必须选择添加整数时是希望对整数进行排序还是不进行排序。
这是我到目前为止添加按钮的代码。
private void buttonAdd_Click(object sender, EventArgs e)
{
listBoxAddedIntegers.Items.Add(textBoxInsert.Text);
textBoxInsert.Text = string.Empty;
//MessageBox.Show(listBoxAddedIntegers.SelectedIndex.ToString());
MessageBox.Show(listBoxAddedIntegers.Items.Count.ToString());
}
这是“单选按钮”排序的代码;
private void radioButtonSorted_CheckedChanged(object sender, EventArgs e)
{
radioButtonSorted.Checked = true;
}
这是“未排序”单选按钮的代码-
private void radioButtonUnsorted_CheckedChanged(object sender, EventArgs e)
{
radioButtonSorted.Checked = false;
}
有没有人对如何将整数添加到列表中有任何建议,以便当用户选择“已排序”单选按钮,然后单击“添加整数”时,然后将整数添加到已排序列表中? 谢谢。
使用单选按钮切换列表框的Sorted
属性。 根据文档 ,它还确保
[as]将项目添加到已排序的列表框,将项目移动到已排序列表中的适当位置
所以,你可以写
private void radioButtonSorted_CheckedChanged(object sender, EventArgs e)
{
if((sender as RadioButton).Checked) listBoxAddedIntegers.Sorted = true;
}
private void radioButtonUnsorted_CheckedChanged(object sender, EventArgs e)
{
if((sender as RadioButton).Checked) listBoxAddedIntegers.Sorted = false;
}
您使用了CheckedChanged
事件。 它不仅会在选中单选按钮时触发,还会在未选中的另一个按钮上触发。 因此,有必要在处理程序中查询实际的检查状态 。
但是有一个缺点: Sorted
仅限于字母顺序。 如果得到1、10、2、3,但期望得到1、2、3、10,则可以用零左键填充整数以得到0001、0002、0003、0010; 或应用类似的解决方案来对数据进行预排序,然后刷新整个列表框。
如果选中排序,这将对列表框中的所有项目进行排序,但我仍然认为没有必要具有2个redio按钮。 您可以将其替换为单个复选框
List<int> numbers = new List<int>();
private void buttonAdd_Click(object sender, EventArgs e)
{
if (radioButtonSorted.Checked)
{
numbers.Clear();
if (!string.IsNullOrEmpty(textBoxInsert.Text))
numbers.Add(int.Parse(textBoxInsert.Text));
foreach (var item in listBoxAddedIntegers.Items)
{
if (item != null)
numbers.Add(int.Parse(item.ToString()));
}
listBoxAddedIntegers.Items.Clear();
numbers.Sort();
foreach (var number in numbers)
listBoxAddedIntegers.Items.Add(number);
}
else
listBoxAddedIntegers.Items.Add(textBoxInsert.Text);
textBoxInsert.Text = string.Empty;
//MessageBox.Show(listBoxAddedIntegers.SelectedIndex.ToString());
MessageBox.Show(listBoxAddedIntegers.Items.Count.ToString());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.