使用消息框确定按钮从列表框中删除双击项目?

时间:2012-05-25 00:05:17

标签: c#

到目前为止,我已经设法在我的双击事件上得到了这么远,并且消息框显示准确,除了我在尝试添加感叹号图标时出现重载错误,但我的主要问题是如何编码以获取所选列表从消息框中单击“确定”按钮时要删除的框项目?

private void statesListBox_MouseDoubleClick(object sender, MouseEventArgs e)
{
    //Select a state to remove from list box
    if (statesListBox.SelectedItem != null)

    if (statesListBox.SelectedItem.ToString().Length != 0)

    MessageBox.Show("Delete" + " " + (statesListBox.SelectedItem.ToString()) 
                    + "   " + "Are you sure?", "Delete" + " " + 
                    (statesListBox.SelectedItem.ToString()));
    if (MessageBoxResult.OK)
}

2 个答案:

答案 0 :(得分:0)

您需要捕获SelectedIndices属性,以便删除项目。如果直接使用此属性,.RemoveAt调用将导致选择更改,并且您无法使用它。同样,您应该在删除多个项目时以反向索引顺序迭代集合,否则循环将在第一个项目之后删除错误的项目。这应该可以解决问题;

int[] indices = (from int i in statesListBox.SelectedIndices orderby i descending select i).ToArray();

foreach (int i in indices)
    statesListBox.Items.RemoveAt(i);

答案 1 :(得分:0)

private void statesListBox_MouseDoubleClick(object sender, MouseEventArgs e)
{
    //Select a state to remove from list box
    if (statesListBox.SelectedItem != null)
        return;

    if (statesListBox.SelectedItem.ToString().Length != 0)
    {            
        if (
            MessageBox.Show("Are you sure you want to delete " + 
                            statesListBox.SelectedItem.ToString() + "?", "Delete" 
                            + statesListBox.SelectedItem.ToString(), 
                            MessageBoxButtons.YesNo, MessageBoxIcon.Information) 
            == DialogResult.Yes
       )
        statesListBox.Items.Remove(statesListBox.SelectedItem);
    }
}

首先要做的事情。

按下“是”时,上面的代码将删除您选择的项目。因为你问一个问题,这就是为什么答案可以是和否的原因。

其次根据您对RJLohan answer的评论(Any idea what is causing the overload error when I try adding the exclamation icon to my message box? I believe it is a error caused by the toString),存在重载错误。经过一番思考后,我猜我得到了为什么以及你正在采取什么错误

您必须将MessageBox.Show称为

MessageBox.Show Method (String, String, MessageBoxIcon)

right syntax

MessageBox.Show Method (String, String, MessageBoxButtons, MessageBoxIcon)

这就是错误必须说"The best overload method match for 'System.Windows.Forms.MessageBox.Show(string, string, System.Windows.MessageBoxButtons)' has some invalid arguments."

的原因

或类似的东西。

相关问题