How to run method on Form Load?

  • Thread starter Thread starter deko
  • Start date Start date
D

deko

The method I want to run when my (Windows Forms app) form loads is an event
triggered by a radio button selection:

private void optColors_CheckedChanged(object sender,
EventArgs e)

But when the form is loading, there is no sender - so the below code fails:

RadioButton opt = (RadioButton)sender; //exception
if (opt.Checked)
{
string strOpt = opt.Name;
setCbo(strOpt);
}

What I need to do is somehow check if the sender is there, and if not, set
strOpt to a default value - something like this:

if (sender) //pseudo code
{
RadioButton opt = (RadioButton)sender;
}
else
{
//code to run on Form Load only
RadioButton opt = this.optColors;
}
if (opt.Checked)
{
string strOpt = opt.Name;
setCbo(strOpt);
}

How do I check for a valid sender? Do I check for EventArgs e instead?

Thanks in advance.
 
Try this is your event-handler (untested):

RadioButton opt = sender as RadioButton
if((opt != null) && (opt.Checked))
{
string strOpt = opt.Name;
setCbo(strOpt);
}
 
RadioButton opt = sender as RadioButton

That seems to do the trick - thanks.

I've still a newbie - what is happening with the "sender as" statement?

This appears to be working:

// all radio buttons in grpSearchBy use same event handler
RadioButton opt = sender as RadioButton;
if (opt != null) // we have an event
{
opt = (RadioButton)sender;
}
else // we do not have an event, so use default for FormMain Load event
{
opt = this.optProductColors;
}

if (opt.Checked)
{
string strOpt = opt.Name;
setCbo(strOpt);
shoCbo(strOpt);
}
 
You really do not need to do the assignment in the 'if' clause. The "sender
as" statement already casts the sender variable to a type of RadioButton. If
sender is null to begin with, or cannot be casted to the RadioButton type,
then 'opt' will be null. So you could rewrite your statement as:

RadioButton opt = sender as RadioButton;
if(opt == null)
{
opt = this.optProductColors;
}

if (opt.Checked)
{
string strOpt = opt.Name;
setCbo(strOpt);
shoCbo(strOpt);
}
 
Back
Top