2012-05-25 48 views
0

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

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) 
} 
+0

这是Winforms还是WPF? – Steve

回答

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); 
+0

谢谢你。它让我疯狂......任何想法当我尝试将惊叹号图标添加到我的消息框时,是什么导致了重载错误?我相信这是由toString引起的错误。 –

+0

我不知道这个问题背后的代码是什么,你还没有发布。 –

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

或类似的东西。

相关问题