Allan Allan - 5 months ago 18
C# Question

How not to allow folderBrowserDialog to be invoked based on a condition?

My code does not allow any characters other than 0-9/a-z to be entered in a textbox. For this, the code used is below, which is a method.

public bool IsValidFilename(string exportName)
{
var regex = new Regex(@"[^a-zA-Z0-9\s]");
if (regex.IsMatch(exportName))
{
MessageBox.Show("Enter only valid characters! (Aa-Zz, 0-9)", MessageBoxButtons.OK, MessageBoxIcon.Information);
};

return true;
}


I have invoked this method in a Button Click event and the messagebox shows up as expected. But succeeding this is an folderBrowserDialog method which opens up irrespective of the result of the above code.

public void btExport_Click(object sender, EventArgs e)
{
IsValidFilename(textBox1.Text);

var dialogResult = folderBrowserDialog.ShowDialog();
}


How do I not allow the application to open up the folderBrowserDialog?

PS: I would like the parent application running and I do not want to use Application.Exit() or this.Close().

Answer Source

Your method already returns a bool, this means you can just do this:

public void btExport_Click( object sender, EventArgs e )
{
    if( IsValidFilename( textBox1.Text ) )
    {
        var dialogResult = folderBrowserDialog.ShowDialog();
    }
}

Your method however will have to return false if it fails:

public bool IsValidFilename(string exportName)
{
    var regex = new Regex(@"[^a-zA-Z0-9\s]");
    if (regex.IsMatch(exportName)) 
    {
        MessageBox.Show("Enter only valid characters! (Aa-Zz, 0-9)", MessageBoxButtons.OK, MessageBoxIcon.Information);
        //If this is the location of the error, put return false here.
        return false;
    };

    return true;
}

1 quick note, shouldn't

if (regex.IsMatch(exportName))

be

if (!regex.IsMatch(exportName)) //!