OnClick Handler

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • =?Utf-8?B?Smlt?=

    OnClick Handler

    In a C# project I have an array of PictureBoxes.
    I form an event handler for each picturebox as it is created using i as an
    index.
    PictureBox1[i].Click += new System.EventHan dler(ClickHandl er);

    In the event handler I would like to determine the index of the clicked box.
    The code below does not return the index.

    public void ClickHandler(Ob ject sender, System.EventArg s e)
    {
    textBox1.Text = sender.ToString ();
    }

    Any help would be appreciated.
    Thanks,
    Jim
  • Peter Duniho

    #2
    Re: OnClick Handler

    On Mon, 05 May 2008 20:45:00 -0700, Jim <Jim@discussion s.microsoft.com
    wrote:
    In a C# project I have an array of PictureBoxes.
    I form an event handler for each picturebox as it is created using i as
    an
    index.
    PictureBox1[i].Click += new System.EventHan dler(ClickHandl er);
    >
    In the event handler I would like to determine the index of the clicked
    box.
    There are at least two approaches I can think of that would be reasonable.

    The first involves using the Tag property of the PictureBox control. You
    can assign the index of the control to the Tag property, and then read it
    back out later in the handler:

    PictureBox1[i].Click += ClickHandler;
    PictureBox1[i].Tag = i;

    and...

    public void ClickHandler(ob ject sender, EventArgs e)
    {
    Control ctl = (Control)sender ;
    int i = (int)ctl.Tag;
    }

    Alternatively, you could use an anonymous method for the handler that
    captures the index, and pass that to a method that actually does the work:

    for (int i = 0; i < PictureBox1.Len gth; i++)
    {
    // Note that you need a local variable that
    // is newly scoped for each iteration of the array,
    // so that each anonymous method gets a new captured
    // variable. Otherwise, they will all wind up using
    // the same variable and thus the same value.

    int iCaptured = i;

    PictureBox1[i].Click += delegate(object sender, EventArgs e)
    { ClickHandler(se nder, iCaptured); };
    }

    and...

    public void ClickHandler(ob ject sender, int i)
    {
    // do stuff with i
    }

    Either should work fine. Using the Tag is probably simpler and easier,
    but if you're already using the Tag for something else, the anonymous
    method approach should be a good alternative.

    Pete

    Comment

    • MichaelC

      #3
      Re: OnClick Handler

      "Peter Duniho" <NpOeStPeAdM@nn owslpianmk.comw rote in message
      news:op.uapsks0 m8jd0ej@petes-computer.local. ..
      There are at least two approaches I can think of that would be reasonable.
      You could just search the array.
      The first involves using the Tag property of the PictureBox control. You
      This sort of thing is generally best avoided as you now have a piece of data
      stored in 2 locations that could report different results. Seeing that we're
      just talking about the user clicking on a picturebox then searching the
      array would be simplest and fast enough. If the array is modified in any way
      then tags don't need to be updated.

      Michael


      Comment

      • Peter Duniho

        #4
        Re: OnClick Handler

        On Mon, 05 May 2008 21:37:33 -0700, MichaelC <mike@nospams.c omwrote:
        "Peter Duniho" <NpOeStPeAdM@nn owslpianmk.comw rote in message
        news:op.uapsks0 m8jd0ej@petes-computer.local. ..
        >There are at least two approaches I can think of that would be
        >reasonable.
        >
        You could just search the array.
        You could. I disagree that it's the cleanest, most elegant approach.
        >The first involves using the Tag property of the PictureBox control.
        >You
        >
        This sort of thing is generally best avoided as you now have a piece of
        data
        stored in 2 locations that could report different results.
        First, the "piece of data" isn't "stored" in two locations. Arguably it's
        represented in two places, but a) it's really only stored in one place,
        and b) there's nothing fundamentally wrong with doing it that way.

        After all, if your objection was legitimate, the whole Control hiearachy
        implementation in the Forms namespace is flawed. It does basically the
        same thing, as does any data structure that maintains a back-reference to
        an element of a collection that refers to an item.
        Seeing that we're
        just talking about the user clicking on a picturebox then searching the
        array would be simplest and fast enough. If the array is modified in any
        way
        then tags don't need to be updated.
        Who said the array would ever be modified in any way?

        I don't disagree that maintaining the Tag property if the containing
        collection is changed is more complicated. However, that wasn't ever a
        stated requirement and even if it was, it's not a problem to reiterate the
        array and reset all the Tag properties if the array changes. As long as
        the collection itself changes less frequently than an object in the
        collection is clicked (which seems likely) you're theoretically better off
        iterating the collection just when it changes, rather than every single
        time a mouse click happens.

        Granted, as long as the array is small (and it ought to be), it's not a
        significant cost either way. But I strongly dispute your criticism that
        the use of the Tag property is somehow an undesirable approach.

        Pete

        Comment

        • Tim Jarvis

          #5
          Re: OnClick Handler

          Peter Duniho wrote:
          You could just search the array.
          >
          You could. I disagree that it's the cleanest, most elegant approach.
          >
          How about making the array a List<PictureBox instead and simply
          doing...

          int i = pictureBoxes.In dexOf((PictureB ox)sender);

          Cheers Tim.

          --

          Comment

          • MichaelC

            #6
            Re: OnClick Handler

            "Peter Duniho" <NpOeStPeAdM@nn owslpianmk.comw rote in message
            news:op.uapuajg f8jd0ej@petes-computer.local. ..
            You could. I disagree that it's the cleanest, most elegant approach.
            I didn't expect you to agree, seeing as you didn't think of it. However, if
            you've got a list of items and want to find the index of the item in that
            list then the simplest method is to search the list. It might not be the
            quickest but we don't need speed here.
            First, the "piece of data" isn't "stored" in two locations.
            Whatever, you know exactly what I meant and are just being argumentitive.
            Arguably it's represented in two places, but a) it's really only stored
            in one place, and b) there's nothing fundamentally wrong with doing it
            that way.
            There is most definately something wrong with storing the same thing twice
            if you have no good to do so. This I thought was fairly well known.
            After all, if your objection was legitimate, the whole Control hiearachy
            implementation in the Forms namespace is flawed. It does basically the
            same thing, as does any data structure that maintains a back-reference to
            an element of a collection that refers to an item.
            Possibly it is, possibly it isn't. You're drawing quite a long bow there
            whatever the case.
            Who said the array would ever be modified in any way?
            No one, but in the case that it is there is zero chance of the index getting
            messed up.
            I don't disagree that maintaining the Tag property if the containing
            collection is changed is more complicated. However, that wasn't ever a
            stated requirement and even if it was, it's not a problem to reiterate the
            array and reset all the Tag properties if the array changes.
            Sure but it's one thing you don't need to do.
            As long as the collection itself changes less frequently than an object
            in the collection is clicked (which seems likely) you're theoretically
            better off iterating the collection just when it changes, rather than
            every single time a mouse click happens.
            Speed is not an issue in this case.
            Granted, as long as the array is small (and it ought to be), it's not a
            significant cost either way. But I strongly dispute your criticism that
            the use of the Tag property is somehow an undesirable approach.
            Less desirable approach Peter.

            Michael


            Comment

            • MichaelC

              #7
              Re: OnClick Handler

              "Tim Jarvis" <tim@jarvis.com .auwrote in message
              news:OX3sqdzrIH A.3780@TK2MSFTN GP03.phx.gbl...
              How about making the array a List<PictureBox instead and simply
              doing...
              >
              int i = pictureBoxes.In dexOf((PictureB ox)sender);
              Don't be silly. Peter's ideas are much simpler than that 1 line of code :-)

              Michael


              Comment

              • Peter Duniho

                #8
                Re: OnClick Handler

                On Mon, 05 May 2008 22:09:51 -0700, Tim Jarvis <tim@jarvis.com .auwrote:
                How about making the array a List<PictureBox instead and simply
                doing...
                >
                int i = pictureBoxes.In dexOf((PictureB ox)sender);
                How is that different from Michael's suggestion? You can do basically the
                same thing with an Array.

                Comment

                • Peter Duniho

                  #9
                  Re: OnClick Handler

                  On Mon, 05 May 2008 22:30:31 -0700, MichaelC <mike@nospams.c omwrote:
                  "Peter Duniho" <NpOeStPeAdM@nn owslpianmk.comw rote in message
                  news:op.uapuajg f8jd0ej@petes-computer.local. ..
                  >You could. I disagree that it's the cleanest, most elegant approach.
                  >
                  I didn't expect you to agree, seeing as you didn't think of it.
                  Don't confuse not mentioning something with not thinking of it.
                  [...]
                  There is most definately something wrong with storing the same thing
                  twice
                  if you have no good to do so. This I thought was fairly well known.
                  I've never heard the phrase "if you have no good to do so", but assuming
                  you mean that you shouldn't store the same thing twice if there's no need,
                  then you are making a tautological argument. You've started with the
                  assumption that there's no need, so of course you come to the conclusion
                  that there's no need.

                  It's hardly a useful conclusion though.
                  >After all, if your objection was legitimate, the whole Control hiearachy
                  >implementati on in the Forms namespace is flawed. It does basically the
                  >same thing, as does any data structure that maintains a back-reference
                  >to
                  >an element of a collection that refers to an item.
                  >
                  Possibly it is, possibly it isn't. You're drawing quite a long bow there
                  whatever the case.
                  I have no idea what you mean here. The phrase "possibly it is, possibly
                  it isn't" adds nothing, as it's a trivially true statement without any
                  actual meaning. You might as well write "it's either true or it's
                  false". The second sentence is a colloqualism I don't recognize. If it's
                  meant to add to the discussion, it's lost on me.
                  >Who said the array would ever be modified in any way?
                  >
                  No one, but in the case that it is there is zero chance of the index
                  getting
                  messed up.
                  There is zero chance of it getting messed up as long as the Tags are
                  updated any time the array is. So?
                  >I don't disagree that maintaining the Tag property if the containing
                  >collection is changed is more complicated. However, that wasn't ever a
                  >stated requirement and even if it was, it's not a problem to reiterate
                  >the
                  >array and reset all the Tag properties if the array changes.
                  >
                  Sure but it's one thing you don't need to do.
                  And iterating over the array every time the mouse is clicked is also one
                  thing you don't _need_ to do. So?
                  >As long as the collection itself changes less frequently than an object
                  >in the collection is clicked (which seems likely) you're theoretically
                  >better off iterating the collection just when it changes, rather than
                  >every single time a mouse click happens.
                  >
                  Speed is not an issue in this case.
                  I did say "theoretically" . But even if we are absolutely positive that
                  speed is not an issue...so what?
                  >Granted, as long as the array is small (and it ought to be), it's not a
                  >significant cost either way. But I strongly dispute your criticism that
                  >the use of the Tag property is somehow an undesirable approach.
                  >
                  Less desirable approach Peter.
                  Fine. I dispute that criticism as well.

                  There's nothing wrong with the approach you've suggested. However,
                  there's absolutely something wrong with the WAY you've suggested it.
                  You've got absolutely no basis for claiming that iterating the array is a
                  superior solution. It's a _different_ and _valid_ solution, to be sure.
                  But other than that, forget it. Any claim you might have regarding it
                  superiority is based solely on your subjective opinion, and like or not
                  your opinion is not a valid basis for claims of superiority.

                  Pete

                  Comment

                  • MichaelC

                    #10
                    Re: OnClick Handler

                    "Peter Duniho" <NpOeStPeAdM@nn owslpianmk.comw rote in message
                    news:op.uapxroe 28jd0ej@petes-computer.local. ..
                    Don't confuse not mentioning something with not thinking of it.
                    Fair enough although if you'd thought of the simplest easiest method I would
                    have thought you'd mention it.
                    I've never heard the phrase "if you have no good to do so", but assuming
                    you mean that you shouldn't store the same thing twice if there's no need,
                    then you are making a tautological argument. You've started with the
                    assumption that there's no need, so of course you come to the conclusion
                    that there's no need.
                    Hardly, my statement was that you would use an alternative method if speed
                    was an issue. As speed is clearly not an issue in this case there is no need
                    to store the same thing twice.
                    It's hardly a useful conclusion though.
                    That is wrong.
                    I have no idea what you mean here. The phrase "possibly it is, possibly
                    it isn't" adds nothing, as it's a trivially true statement without any
                    actual meaning.
                    That was the point silly!!! It was meant to be trivial to reflect your
                    trivial statement.
                    You might as well write "it's either true or it's false". The second
                    sentence is a colloqualism I don't recognize. If it's meant to add to
                    the discussion, it's lost on me.
                    Drawing a long bow means you're trying to associate 2 things that are really
                    quite different and drawing incorrect conclusions by doing that.
                    There is zero chance of it getting messed up as long as the Tags are
                    updated any time the array is. So?
                    So what you're saying is there's zero chance of it getting messed up if you
                    don't mess it up. The FACT is there is a possibility of it getting messed
                    up. That possibility might be small but it's not zero as you state. I prefer
                    to eliminate any potential sources of bugs. You could even have someone else
                    come along and decide to use the Tag property for something else.
                    And iterating over the array every time the mouse is clicked is also one
                    thing you don't _need_ to do. So?
                    As Jim stated you can get the framework to do it for you.
                    Fine. I dispute that criticism as well.
                    Of course you do, as usual.
                    There's nothing wrong with the approach you've suggested. However,
                    there's absolutely something wrong with the WAY you've suggested it.
                    You've got absolutely no basis for claiming that iterating the array is a
                    superior solution. It's a _different_ and _valid_ solution, to be sure.
                    But other than that, forget it. Any claim you might have regarding it
                    superiority is based solely on your subjective opinion, and like or not
                    your opinion is not a valid basis for claims of superiority.
                    No, I've provided some fairly significant reasons as to why it's superior,
                    you've just ignored them. (remember the joke "I haven't listed to a single
                    complaint" :-)

                    Michael



                    Comment

                    • Tim Jarvis

                      #11
                      Re: OnClick Handler

                      Peter Duniho wrote:
                      How is that different from Michael's suggestion? You can do
                      basically the same thing with an Array.
                      Well its not really :-)

                      I was just pointing out that a "search" need not necessarily be
                      something as onerous as...

                      for(int i = 0;i < pictureBoxes.Le ngth();i++)
                      {
                      if ( pictureBoxes[i] == (PictureBox)sen der)
                      {
                      index = i;
                      break;
                      }
                      }

                      However I also forgot that he could also just use the Array.IndexOf
                      static method so he doesn't even need to use a List or Collection.

                      Anyhoo, I wasn't actually dissing your approach either, I am on
                      nobody's "side" here. Its true that I am also not a particular fan of
                      using Tag properties for this kind of thing, but I am also pragmatic
                      enough to agree that in most cases it's no particular problem.

                      Cheers Tim.

                      --

                      Comment

                      • Peter Duniho

                        #12
                        Re: OnClick Handler

                        On Mon, 05 May 2008 23:37:04 -0700, MichaelC <mike@nospams.c omwrote:
                        [...]
                        >I've never heard the phrase "if you have no good to do so", but assuming
                        >you mean that you shouldn't store the same thing twice if there's no
                        >need,
                        >then you are making a tautological argument. You've started with the
                        >assumption that there's no need, so of course you come to the conclusion
                        >that there's no need.
                        >
                        Hardly, my statement was that you would use an alternative method if
                        speed
                        was an issue.
                        No, that wasn't your statement at all. You wrote: "There is most
                        definately [sic] something wrong with storing the same thing twice if you
                        have no good to do so. This I thought was fairly well known." That
                        contains no reference to "speed", nor is speed the only criteria here.
                        The fact is, in its way, using the Tag property is _simpler_ than your
                        proposal.
                        As speed is clearly not an issue in this case there is no need
                        to store the same thing twice.
                        Again with the tautology. You start with the unfounded assumption that
                        speed is the only advantage that using the Tag property has, as if it's
                        axiomatic. Well, it's not. You are simply taking as an assumption the
                        very thing you're trying to prove.
                        >I have no idea what you mean here. The phrase "possibly it is, possibly
                        >it isn't" adds nothing, as it's a trivially true statement without any
                        >actual meaning.
                        >
                        That was the point silly!!! It was meant to be trivial to reflect your
                        trivial statement.
                        What trivial statement? And why are you confusing the statement I
                        actually wrote, that the phrase is "trivially true", with a more general
                        statement that it's "trivial"?

                        You may well have intended your statement to be trivial, but that wasn't
                        the observation I was making.
                        >You might as well write "it's either true or it's false". The second
                        >sentence is a colloqualism I don't recognize. If it's meant to add to
                        >the discussion, it's lost on me.
                        >
                        Drawing a long bow means you're trying to associate 2 things that are
                        really
                        quite different and drawing incorrect conclusions by doing that.
                        In the context of your overly broad generalization, you claim these
                        examples are "really quite different"? That's rich.

                        The fact is, storing redundant information is a common technique.
                        Asserting that it's always the wrong thing to do flies the face of
                        timeless, useful engineering strategies.
                        >There is zero chance of it getting messed up as long as the Tags are
                        >updated any time the array is. So?
                        >
                        So what you're saying is there's zero chance of it getting messed up if
                        you
                        don't mess it up.
                        No. My statement and your attempt to paraphrase it are quite different
                        from each other.
                        The FACT is there is a possibility of it getting messed
                        up.
                        It's possible to mess anything up, if you're careless enough, including
                        your own suggestion. There's nothing unduly complicated about using the
                        Tag property as a back-reference that would introduce some significant
                        risk of it being messed up.
                        [...]
                        >And iterating over the array every time the mouse is clicked is also one
                        >thing you don't _need_ to do. So?
                        >
                        As Jim stated you can get the framework to do it for you.
                        Actually, since we're talking about an array here, _I_ stated that. Tim
                        (not Jim) stated that you can get the framework to do it if you use a
                        List<T>.

                        Regardless, whether the framework does it or not, it's not something you
                        _need_ to do. The question of whether you write the loop yourself or call
                        a .NET method that already has the loop is irrelevant.
                        >Fine. I dispute that criticism as well.
                        >
                        Of course you do, as usual.
                        You're right. It's quite common for me to dispute things that are
                        incorrect. What's your point?
                        >[...] Any claim you might have regarding it
                        >superiority is based solely on your subjective opinion, and like or not
                        >your opinion is not a valid basis for claims of superiority.
                        >
                        No, I've provided some fairly significant reasons as to why it's
                        superior,
                        I haven't seen a single "fairly significant reason" posted by you. Only
                        your inflated sense of the importance of the reasons you've stated causes
                        you to describe them as "fairly significant". You've failed to
                        demonstrate in any sort of logically sound way that the reasons are
                        "fairly significant". We have only your subjective assertion that they
                        are so.

                        Pete

                        Comment

                        • Chris Shepherd

                          #13
                          Re: OnClick Handler

                          Jim wrote:
                          In a C# project I have an array of PictureBoxes.
                          I form an event handler for each picturebox as it is created using i as an
                          index.
                          PictureBox1[i].Click += new System.EventHan dler(ClickHandl er);
                          >
                          In the event handler I would like to determine the index of the clicked box.
                          The code below does not return the index.
                          >
                          public void ClickHandler(Ob ject sender, System.EventArg s e)
                          {
                          textBox1.Text = sender.ToString ();
                          }
                          >
                          Any help would be appreciated.
                          The lengthy back and forth elsewhere in this thread aside, can I just ask why
                          you have this particular design? What are you attempting to solve with this?

                          Does the Array of PictureBoxes stick around after instantiation? If so, why?

                          PictureBox + click event makes me think slideshow.

                          Chris.

                          Comment

                          • MichaelC

                            #14
                            Re: OnClick Handler

                            "Peter Duniho" <NpOeStPeAdM@nn owslpianmk.comw rote in message
                            news:op.uap0u4n m8jd0ej@petes-computer.local. ..
                            On Mon, 05 May 2008 23:37:04 -0700, MichaelC <mike@nospams.c omwrote:
                            Test...

                            Sent three replies so far which haven't appeared.

                            Michael


                            Comment

                            Working...