additem和 removeitem方法添加或者删除listbox控件中的项目

additem和 removeitem方法添加或者删除listbox控件中的项目,第1张

如果不能添加重复项,如下

private void AddItem_Click(object sender, EventArgs e)

{

string addItem = textBox1.Text.Trim()

if (!string.IsNullOrEmpty(addItem) &&!listBox1.Items.Contains(addItem))

{

listBox1.Items.Add(addItem)

}

}

private void RemoveItem_Click(object sender, EventArgs e)

{

string removeItem = textBox1.Text.Trim()

if (!string.IsNullOrEmpty(removeItem) &&listBox1.Items.Contains(removeItem))

{

listBox1.Items.Remove(removeItem)

}

}

如果可以添加重复项,如下

添加:把AddItem_Click中!listBox1.Items.Contains(addItem)删了

删除:如果想一个一个删就不改,如果想一起删就改成:

private void RemoveItem_Click(object sender, EventArgs e)

{

string removeItem = textBox1.Text.Trim()

if (!string.IsNullOrEmpty(removeItem))

{

while (listBox1.Items.Contains(removeItem))

{

listBox1.Items.Remove(removeItem)

}

}

}

思路如下:

1、Listbox本身并不带有删除和添加的功能,需要额外写代码

2、对于删除Listbox中的元素可以利用 AddItem()、RemoveItem()方法

3、如果是通过点击listbox 删除表中的元素。这需要给listbox添加事件。在事件中添加代码删除表格中的数据。

//首次加载动态添加

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

for (int i = 0i <3i++)

{

int j = 0

j += i

this.ListBox1.Items.Add(j.ToString())

}

}

}

//删除按钮单击事件,单击删除选中的项。

protected void Button1_Click(object sender, EventArgs e)

{

string i = this.ListBox1.SelectedValue

ListBox1.Items.Remove(i)

}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/bake/11603466.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-17
下一篇2023-05-17

发表评论

登录后才能评论

评论列表(0条)

    保存