none
OpenFileDialog show error without closing the dialog RRS feed

  • Question

  • Hi,

    I am using below code to select a photo and I want to allow selcting photoz upto 1 MB only.

    In the below code, when the user clicks OK it will close the dialog and then display the error message but how can I show the message without closing the box so use can select another photo?

    OpenFileDialog dialogPicture = new OpenFileDialog();
    dialogPicture.Title = "Employee Photo";
    
    if (dialogPicture.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        var file_size = new FileInfo(dialogPicture.FileName).Length;
    
        if (file_size > 1048576)
        {
            XtraMessageBox.Show("File is larger than 1MB!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return;
        }
    
    }
    

    Thanks,

    Jassim

    Wednesday, December 16, 2015 2:20 PM

Answers

  • You can use FileOK event

    https://msdn.microsoft.com/en-us/library/system.windows.forms.filedialog.fileok(v=vs.110).aspx

    private void Form1_Load(object sender, EventArgs e)
    {
    	OpenFileDialog dialog = new OpenFileDialog();
    	dialog.FileOk += dialog_FileOK;
    
    	if (dialog.ShowDialog == Windows.Forms.DialogResult.OK) {
    	}
    }
    
    private void dialog_FileOK(object sender, CancelEventArgs e)
    {
    	OpenFileDialog dialog = sender;
    	var file_size = new FileInfo(dialog.FileName).Length;
    
            if (file_size > 1048576)
          {
              XtraMessageBox.Show("File is larger than 1MB!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
              e.Cancel = true;
         }
    }



    Gaurav Khanna | Microsoft .NET MVP | Microsoft Community Contributor


    • Edited by Khanna Gaurav Wednesday, December 16, 2015 4:29 PM
    • Proposed as answer by Blackwood Wednesday, December 16, 2015 4:31 PM
    • Marked as answer by Jassim Rahma Wednesday, December 16, 2015 9:34 PM
    Wednesday, December 16, 2015 4:26 PM