Search code examples
c#winformsformsmessageboxdialogresult

Message box closing form erradically


I use a message box to make sure if the user wants to delete a row from the gridview however no matter what answer they give it closes the form and returns to form1

This is where the viewTransactions form is loaded this code is in Form1

 private void btnViewTrans_Click(object sender, EventArgs e)
 {
    viewTransactions = new View_Transactions(newList);
    if (viewTransactions.ShowDialog() == DialogResult.OK)
    {
       newList.Equals(viewTransactions.getList());
    }

 }   

This is where the messageBox is shown in the viewTransaction form

    ///////////////////////////////
    //Remove an item from the list
    private void button3_Click(object sender, EventArgs e)
    {
        DialogResult result = new DialogResult();
        result = MessageBox.Show("Are you sure you want to delete this element?", "Confirmation", MessageBoxButtons.YesNoCancel);
        if (result == DialogResult.Yes)
        {
            foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)
            {
                tmpList.remove(item.Index);//remove item from tmpList used to update the passed in list                    
                dataGridView1.Rows.RemoveAt(item.Index);//remove the item from the dataGrid
            }
        }
    }

I had no problems with the code until I used the messagebox to display a warning. I believe that the DialogResult is being passed to the other ShowDialog and that is why it is closing out my form.


Solution

  • I solved it by adding the this.dialogResult = dilaogResult.None; As soon as the button3_Click was called the base.DialogResult went to cancel for some reason

    Steve it would still close when I tried your line, but thanks for telling me how to look that was how I figured it out

    private void button3_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.None;
            DialogResult result = new DialogResult();
            result = MessageBox.Show("Are you sure you want to delete this element?", "Confirmation", MessageBoxButtons.YesNo);
            if (result == DialogResult.Yes)
            {
                foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)
                {
                    tmpList.remove(item.Index);//remove item from tmpList used to update the passed in list                    
                    dataGridView1.Rows.RemoveAt(item.Index);//remove the item from the dataGrid
                }
            }
    
        }