W.Donald W.Donald - 28 days ago 5
C# Question

There is no argument given that corresponds to the required formal parameter 'sender'

I got this method here:

public void textBoxValid(object sender, CancelEventArgs e)
{
string error = null;
string pattern = @"\,\";
if(Regex.IsMatch(priceTextBox.Text, pattern))
{
error = "Please use [.] instead of [,]";
e.Cancel = true;
}
errorProvider1.SetError((Control) sender, error);
}


And when I'm calling it here:

private void enterButton_Click(object sender, EventArgs e)
{
textBoxValid();
//Write all data to a file.
using (StreamWriter sw = new StreamWriter(@"c:\event.txt", true))
{
sw.WriteLine(priceTextBox.Text + "," + eventTextBox.Text + "," + descriptionTextBox.Text + ","
+ DateTimePicker.Value + "," + DayUpDown.Value);
}
clearTextBoxes();
}


I'm getting an error saying:


There is no argument given that corresponds to the required formal
parameter 'sender' of 'WriteEventForm.textBoxValid(object,
CancelEventArg)'


Could one of you, fine people, point out what am I doing wrong?
Thank you.

Answer

At textBoxValid(), you're calling a method that has two non-optional parameters with zero arguments. You can't do that in C#.

You seem to want to validate the input of a textbox upon the clicking of a button, and prevent that click event from proceeding if the input is invalid. Now to fix your code in a non-idiomatic way, would be to change the method entirely:

public bool ValidateTextBox(TextBox textBoxToValidate)
{
    string error = null;
    string pattern = @"\,\";
    if(Regex.IsMatch(textBoxToValidate.Text, pattern))
    {
        error = "Please use [.] instead of [,]";
        errorProvider1.SetError(textBoxToValidate, error);
        return false;
    }

    return true;
}

Because the sender you have in enterButton_Click() will be the button, not the textbox. So you'll need to provide a reference to the textbox that you want to validate, and then inspect the return value of the method:

private void enterButton_Click(object sender, EventArgs e)
{
    if (!ValidateTextBox(priceTextBox))
    {       
        return;
    }

This will fix your problem for now. But then still you're not using the ErrorProvider as it's meant to.