我正在一个简单的应用程序上,该程序将字符串添加/删除到数组中并在ListBox中显示。
我的代码仅显示在textBox中键入的最新值,
private void Add_Click(object sender, EventArgs e)
{
string add = textBox1.Text;
List<string> ls = new List<string>();
ls.Add(add);
String[] terms = ls.ToArray();
List.Items.Clear();
foreach (var item in terms)
{
List.Items.Add(item);
}
}
private void Delete_Click(object sender, EventArgs e)
{
}
此代码没有任何意义。您将一个项目添加到列表中,然后将其转换为一个数组(仍然包含一个项目),最后遍历该数组,这当然会将一个项目添加到先前清除的列表框中。因此,您的列表框将始终只包含一个项目。为什么不直接添加项目呢?
private void Add_Click(object sender, EventArgs e)
{
List.Items.Add(textBox1.Text);
}
private void Delete_Click(object sender, EventArgs e)
{
List.Items.Clear();
}
同时清除中的列表框,Delete_Click
而不是Add_Click
。
如果您希望将项目保留在单独的集合中,请使用List<string>
,并将其分配给DataSource
列表框的属性。
每当您希望更新列表框时,都对其进行分配null
,然后重新分配该列表。
private List<string> ls = new List<string>();
private void Add_Click(object sender, EventArgs e)
{
string add = textBox1.Text;
// Avoid adding same item twice
if (!ls.Contains(add)) {
ls.Add(add);
RefreshListBox();
}
}
private void Delete_Click(object sender, EventArgs e)
{
// Delete the selected items.
// Delete in reverse order, otherwise the indices of not yet deleted items will change
// and not reflect the indices returned by SelectedIndices collection anymore.
for (int i = List.SelectedIndices.Count - 1; i >= 0; i--) {
ls.RemoveAt(List.SelectedIndices[i]);
}
RefreshListBox();
}
private void RefreshListBox()
{
List.DataSource = null;
List.DataSource = ls;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句