473,473 Members | 2,286 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Pretty easy question, i'd assume..

Hello all,

I have an form to Enter a Name with letters from A to Z in buttons.

When you click a button, it should append the text associated with
that button to a text box.

Instead of having an EventHandler for every button with a click event
of:

private void btnA_Click(object sender, System.EventArgs e)
{
txtNameField.AppendText("A");
}

And so on...

Is there a way to shorten this, such as have just the 1 Event Handler
for all buttons? I was thinking something along the lines of this:

private void buttonLetter_Click(object sender, System.EventArgs e)
{
txtNameField.AppendText(letter);
}

private void AppendLetter(letter)
{
txtNameField.AppendText(letter);
}

I hope you realise what i'm talking about here.
Nov 16 '05 #1
10 1514
Brian <br************@gmail.com> wrote:
I have an form to Enter a Name with letters from A to Z in buttons.

When you click a button, it should append the text associated with
that button to a text box.

Instead of having an EventHandler for every button with a click event
of:

private void btnA_Click(object sender, System.EventArgs e)
{
txtNameField.AppendText("A");
}

And so on...

Is there a way to shorten this, such as have just the 1 Event Handler
for all buttons?


Absolutely. Use one event handler, and use the "sender" parameter to
find out which button was pressed.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #2

"Brian" wrote...
I have an form to Enter a Name with letters from A to Z in buttons.

When you click a button, it should append the text associated with
that button to a text box.

Instead of having an EventHandler for every button with a click event
of:

private void btnA_Click(object sender, System.EventArgs e)
{
txtNameField.AppendText("A");
}

And so on...

Is there a way to shorten this, such as have just the 1 Event Handler
for all buttons?


I guess that you have each letter as the Label of the buttons?

In that case you could have a method like:

private void buttonLetter_Click(object sender, System.EventArgs e)
{
Button b = (Button) sender;
txtNameField.AppendText(b.Text);
}

If you have something else in your labels, you could possibly use the Tag
property of the buttons instead.

// Bjorn A

Nov 16 '05 #3
Instead of DoubleClick on yout button to create an eventhandler. You can make
an eventhandler bij typing in a name in the propertieswindow.

In the evenhandler you could typecast the sender parameter to a button and
read a
describing property like Text or Tag.

string letter = ((Button)Sender).Tag
Nov 16 '05 #4
And if you don't use Visual Studio, you would do this like:

private void btnAll_Click(object sender, System.EventArgs e){
txtNameField.AppendText(((Button)sender).Label);
}
Then in OnInit...

override protected void OnInit(EventArgs e){
btnA.Click += new EventHandler(btnAll_Click);
btnB.Click += new EventHandler(btnAll_Click);
...
base.OnInit(e)
}

You can substitute double clicks if you want, but that would be sort of
annoying.

Marinus Holkema wrote:
Instead of DoubleClick on yout button to create an eventhandler. You can make
an eventhandler bij typing in a name in the propertieswindow.

In the evenhandler you could typecast the sender parameter to a button and
read a
describing property like Text or Tag.

string letter = ((Button)Sender).Tag

Nov 16 '05 #5
Or, if you really wanna save typing (clicking), you could loop over the
controls on the buttons' container...

System.EventHandler alphaBtnClickHdlr = new
System.EventHandler(alphaButtonClick);
foreach ( Control c in alphaButtonPanel.Controls )
{
if ( c is System.Windows.Form.Button )
{
c.Click += alphaBtnClickHdlr;
}
}

This handles all 26 buttons, plus any additional characters you may decide
you need later. This of course assumes you have a panel with no other other
buttons besides those you want to attach the event to. Alternatively, you
could have way to identify the type (it is a special derived type that has a
property to hold the character to append, or it implements a special
interface.) Then you could check ( c is MySpecialButtonType). Of course,
that would be overkill for what you ask, but I do have an ap with some
special types (each containing a number of custom properties) that implement
a common interface, and I use that kind of structure for it.

Rachel

"Mike Newton" <MN*****@discussions.microsoft.com> wrote in message
news:uw**************@TK2MSFTNGP11.phx.gbl...
And if you don't use Visual Studio, you would do this like:

private void btnAll_Click(object sender, System.EventArgs e){
txtNameField.AppendText(((Button)sender).Label);
}
Then in OnInit...

override protected void OnInit(EventArgs e){
btnA.Click += new EventHandler(btnAll_Click);
btnB.Click += new EventHandler(btnAll_Click);
...
base.OnInit(e)
}

You can substitute double clicks if you want, but that would be sort of
annoying.

Marinus Holkema wrote:
Instead of DoubleClick on yout button to create an eventhandler. You can
make an eventhandler bij typing in a name in the propertieswindow.

In the evenhandler you could typecast the sender parameter to a button
and read a describing property like Text or Tag. string letter =
((Button)Sender).Tag

Nov 16 '05 #6
Rachel Suddeth <ra****@bldhound.com> wrote:
Or, if you really wanna save typing (clicking), you could loop over the
controls on the buttons' container...

System.EventHandler alphaBtnClickHdlr = new
System.EventHandler(alphaButtonClick);
foreach ( Control c in alphaButtonPanel.Controls )
{
if ( c is System.Windows.Form.Button )
{
c.Click += alphaBtnClickHdlr;
}
}

This handles all 26 buttons, plus any additional characters you may decide
you need later. This of course assumes you have a panel with no other other
buttons besides those you want to attach the event to. Alternatively, you
could have way to identify the type (it is a special derived type that has a
property to hold the character to append, or it implements a special
interface.) Then you could check ( c is MySpecialButtonType). Of course,
that would be overkill for what you ask, but I do have an ap with some
special types (each containing a number of custom properties) that implement
a common interface, and I use that kind of structure for it.


I think that rather than generate the event handlers separately, I'd
just generate the buttons and the event handlers in one go:

for (char c = 'A'; c <= 'Z'; c++)
{
Button b = new Button();
b.Text = c.ToString();
...
b.Click += new EventHandler (...);
Controls.Add(b);
}

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #7
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
. . .

I think that rather than generate the event handlers separately, I'd
just generate the buttons and the event handlers in one go:

for (char c = 'A'; c <= 'Z'; c++)
{
Button b = new Button();
b.Text = c.ToString();
...
b.Click += new EventHandler (...);
Controls.Add(b);
}

That depends on whether you want to use the designer to lay out the look of
the buttons. If you do, I think you have to let the designer define the
buttons (am I right?) Depending on how you want them to look, it might be
easier to generate them of course. But even if you do use the designer, you
don't have to attach the events through the designer. Rather than going to
26+ different controls and pulling up the right function definition from the
designer's list, you could do it in 6 lines of code, either late in the
constructor, or during a form_load or other such event. Of course, you could
probably select all the buttons, and only click once to attach them all, but
I like the loop because it will give the event to new buttons automatically
(and prevents you from accidentally missing one when you select them all.)

-Rachel
Nov 16 '05 #8
Rachel Suddeth <ra****@bldhound.com> wrote:
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
. . .

I think that rather than generate the event handlers separately, I'd
just generate the buttons and the event handlers in one go:

for (char c = 'A'; c <= 'Z'; c++)
{
Button b = new Button();
b.Text = c.ToString();
...
b.Click += new EventHandler (...);
Controls.Add(b);
}

That depends on whether you want to use the designer to lay out the look of
the buttons. If you do, I think you have to let the designer define the
buttons (am I right?)


Yes, unfortunately I believe that's true.

However, if you've got 26 buttons, it's going to be very tedious to
create all the buttons in the designer, and you'll end up with hideous
code (26 member variables declared for no good reason, for instance -
and unless you rename them manually, they'll all have nasty names,
too).

Of course, you can design the rest of the form in the designer only
write the code to add the buttons.

Then again, I have a bit of a bias against the designer - I feel it
tends to generate code which has far more member variables than are
required, and isn't nice code to read or maintain. It makes things
quicker to start with at the expense of long term code maintainability.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #9
Yes, in the form or class' constructor add the following

this.Button_Click+= new System.EventHandler(nameofmethod);
this.Button1_Click+= new System.EventHandler(nameofmethod);
this.Button2_Click+= new System.EventHandler(nameofmethod);
etc.

with regards,
J.V.Ravichandran
- http://www.geocities.com/
jvravichandran
- http://www.411asp.net/func/search?
qry=Ravichandran+J.V.&cob=aspnetpro
- http://www.southasianoutlook.com
- http://www.MSDNAA.Net
- http://www.csharphelp.com
- http://www.poetry.com/Publications/
display.asp?ID=P3966388&BN=999&PN=2
- Or, just search on "J.V.Ravichandran"
at http://www.Google.com

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #10

"Jon Skeet [C# MVP]" wrote in message
news:MP************************@msnews.microsoft.c om...
Rachel Suddeth <ra****@bldhound.com> wrote:
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
>> . . .
> I think that rather than generate the event handlers separately, I'd
> just generate the buttons and the event handlers in one go:
>
> for (char c = 'A'; c <= 'Z'; c++)
> {
> Button b = new Button();
> b.Text = c.ToString();
> ...
> b.Click += new EventHandler (...);
> Controls.Add(b);
> }
>

That depends on whether you want to use the designer to lay out the look
of
the buttons. If you do, I think you have to let the designer define the
buttons (am I right?)


Yes, unfortunately I believe that's true.

However, if you've got 26 buttons, it's going to be very tedious to
create all the buttons in the designer, and you'll end up with hideous
code (26 member variables declared for no good reason, for instance -
and unless you rename them manually, they'll all have nasty names,
too). ...


This is true. And if you just wanted a nice neat grid full of buttons, it
would be so much easier to generate them. But what if you need them in an
order that's not easy to generate, in a layout where the locations aren't
easy to calculate (in this case, say you want them in qwerty layout?) What
if you have some buttons that you want to be a special size? Although
there's a lot about the designer that's tedious, it is easier than trying to
guess at sizes and locations, then running, then fixing, maybe 8 or 10 times
before it looks right... Then if you want to add another button (say tab
and shift) then you have to move everything over to make room for them, and
that means you have to change the location of all those other buttons you
previously calculated locations for by hand... that's messy. It is possible
to separate the code you're actually going to write from the designer code
(using regions, or by understanding where the designer puts code, and
avoiding mixing yours up there. Also, by putting as much of your code as
reasonable into separate classes or components - yes, so that you only use
the designer where it's actually helpful.) That way you (in theory) never
need to look at the ugly code the desiger makes... just look at the designer
results for that stuff.

What would be nice is if you could generate the buttons early in the
constructor, and then have the designer notice them, and draw them, and let
you change the sizes/locations that get set in InitializeComponent. That is
my fantasy :-)
Nov 16 '05 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Christopher Benson-Manica | last post by:
I need a simple HTML element whose text I can change dynamically. What is it? (it doesn't seem to be <div>, since I can't seem to find what properties a <div> has...) -- Christopher...
36
by: No Spam | last post by:
Dear fellow Access 2003 Users, Is there a way to trim all of the fields in a table in one swoop using VBA (preferred) or a query? Right now, I am using an update query and updating EACH field...
16
by: Terry McNamee | last post by:
return arr.Length == 0 ? null : arr.ToString(); Can anyone tell me what this syntax means? Does it basically mean if arr.Length is equal to 0 then return null, else return the item in the...
3
by: Jason | last post by:
I'm using asp.net to create a staff directory based on Active Directory, and I'm sure this is an easy question, but I can't seem to find anything about it in the newsgroups: I know it's possible...
1
by: Mad Scientist Jr | last post by:
can someone explain how to simply populate a grid in .net ? the way i understand it, there is no more msflexgrid, and instead is this new control that has to be tied to a dataset, and it is a real...
6
by: tshad | last post by:
I am playing with Inheritance and want to make sure I understand it. I have the following Classes: ******************************************* Public Class AuthHeader:Inherits SoapHeader Public...
37
by: Prafulla T | last post by:
Assume that an integer pointer x is declared in a "C" program as int *x; Further assume that the location of the pointer is 1000 and it points to an address 2000 where value 500 is stored in 4...
12
by: kostas | last post by:
Hi I was asked to propose an interview question for C/C++ programmers (CAD/CAE software) I came up with the following...
27
by: mbatestblrock | last post by:
Okay, I know this probably going to be flat out the dumbest question anyone has seen on here, and I apologize for this. I am using a sendmail.php script and it works just fine but for some reason...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.