0

So far I have managed to get this far on my double click event and have the message box showing accurately except I get a overload error when trying to add exclamation icon, But my main issue is how to code to get the selected list box item to delete when clicking ok button from message box?

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)
}
4

2 回答 2

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);
于 2012-05-25T00:33:28.023 回答
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 答案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)

正确的语法

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."

或类似的东西。

于 2012-05-25T05:31:48.340 回答