Getting a control's name.

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a form with 13 pairs of radio buttons to record yes/no answers.
Consider the following code snippet;

private void OnRBClick(object sender, System.EventArgs e)
{
RadioButton rb = (RadioButton) sender;
}

This is a generic click handler that could be used to handle click responses
from all 26 of the radio buttons on the page – providing I could
differentiate between them. Is there some way to get the control to cough up
its name? I don’t mean the name of its type like you can get through
rb.GetType().Name, I mean the name I gave in the properties window, the name
it is declared as.

If I could do that I could write a select statement to update the
appropriate column in the database, and it seems to me like that would be
more memory efficient than supporting 13 different event handlers for each of
the radio button pairs.

Bill
 
public static string GetControlName(object SourceControl)
{
FieldInfo[] fi =
((Control)SourceControl).Paren­t.GetType().GetFields(BindingF­lags.NonPublic
| BindingFlags.Instance |BindingFlags.Public |
BindingFlags.IgnoreCase);


foreach(FieldInfo f in fi)
{
if(f.GetValue(((Control)Source­Control).Parent).Equals(Source­Control))
return f.Name;
}
return null;



}


--
Chris Tacke
Co-founder
OpenNETCF.org
Are you using the SDF? Let's do a case study.
Email us at d c s @ o p e n n e t c f . c o m
http://www.opennetcf.org/donate
 
Bill,

In addition to Chris's suggestion, do you really need the *name* of the
control or do you just need to know which control it is? For example instead
of comparing the name to "MyControl" how about just checking to see if (rb
== MyControl).

Ginny Caughey
..NET Compact Framework MVP
 
Bill said:
I have a form with 13 pairs of radio buttons to record yes/no answers.

Bill,

I come from a Borland background, and one of the nice features of every
control is an integer value called Tag. So for your request, you would
set a unique Tag value to every control, and when the event fires just
examine this value.

You can extend any Control by using something like....

public class MyRadioButton : RadioButton
{
private int tag;

public MyRadioButton ()
{
this.tag = 0;
}

public int Tag
{
get { return ( this.tag ); }
set { this.tag = value; }
}
}
 
Back
Top