views:

3086

answers:

2

So i'm not really sure why this is happening but I'm running through some DataRows where I have the control name, property, and value that I want to set. Everything works fine except when I set the TEXT property of a button. For some reason, the click event is called...

Here's some of the code I've got:

string controlName, value, property;
Control currentControl = null;
System.Reflection.PropertyInfo propertyInfo = null;

// run through all rows in the table and set the property
foreach (DataRow r in languageDataset.Tables[_parentForm.Name].Rows)
{
  controlName = r["ControlName"].ToString().ToUpper();
  value = r["Value"].ToString();
  property = r["Property"].ToString();

  // check all controls on the form
  foreach (Control c in formControls)
  {
    // only change it if its the right control
    if (c.Name.ToUpper() == controlName)
    {
      propertyInfo = c.GetType().GetProperty(property);

      if (propertyInfo != null)
        propertyInfo.SetValue(c, value, null);  ******Calls Event Handler?!?!******
      //

      currentControl = c;
      break;
    }
  }
}

So why in the world would it call the event handler when setting the value? Here's what I'm setting it with that's causing this:

<SnappletChangePassword>  
  <ControlName>buttonAcceptPassword</ControlName>
  <Property>Text</Property>  
  <Value>Accept</Value>
</SnappletChangePassword>
+2  A: 

I can't reproduce this with a simple short but complete program:

using System;
using System.Drawing;
using System.Reflection;
using System.Windows.Forms;

class Test
{
    static void Main()
    {
        Button goButton = new Button { 
            Text = "Go!",
            Location = new Point(5, 5)
        };

        Button targetButton = new Button {
            Text = "Target",
            Location = new Point(5, 50)
        };
        goButton.Click += (sender, args) => SetProperty(targetButton, "Text", "Changed");
        targetButton.Click += (sender, args) => MessageBox.Show("Target clicked!");

        Form f = new Form { Width = 200, Height = 120,
                Controls = { goButton, targetButton }
        };
        Application.Run(f);
    }

    private static void SetProperty(object target, string propertyName, object value)
    {
        PropertyInfo property = target.GetType().GetProperty(propertyName);
        property.SetValue(target, value, null);
    }
}

Can you come up with a similarly complete program which does demonstrate it?

Jon Skeet
A: 

Sadly, no I couldn't reproduce it either. I'm not sure what was causing it but all I did to fix it was delete the button and put it back on there.

not sure what it was, but thanks for the code.

You didn't write that in .Net2.0 did you?

Miles