简体   繁体   中英

c# DataBinding to string property on a Generic

I'm trying to Databind to my custom dictionary class. In formLoad, I can bind to Car.Desc but I cannot bind to RatesCache.Desc. They are both public string properties.

What am I missing?

Thanks!

System.ArgumentException was unhandled Message="Cannot bind to the property or column Desc on the DataSource.\r\nParameter name: dataMember" Source="System.Windows.Forms" ParamName="dataMember"

    public class RatesCache : Dictionary<int, Rate>
    {
        public string Desc { get; set; }
    }

    public class Car
    {
        public string Desc { get; set; }
    }

    static Car car = new Car();

    static RatesCache rc = new RatesCache();

    private void Form1_Load(object sender, EventArgs e)
    {
        rc.Desc = "hello too";
        car.Desc = "Im a car";
        textBox1.DataBindings.Add("Text", rc, "Desc");
    }
private void Form1_Load(object sender, EventArgs e)
{
    rc.Desc = "hello too";
    car.Desc = "Im a car";
    textBox1.DataBindings.Add("Text", rc, "Desc");
    textBox1.TextChanged .TextChanged += _textBox1_TextChanged;
}

private void _messagesReceviedLabel_TextChanged(object sender, EventArgs e)
{
    _textBox1.Text = rc.Desc.ToString();
}

public class RatesCache : Dictionary<int, Rate>
{
    public string Desc { get; set; }

    public override string ToString()
    {
        return Desc;
    }
}

My guess is that because your class is inheriting from a Dictionary which is a Collection, it throws off the DataBinding for the textbox. Windows Forms has it's own way of dealing with databinding to a collection different then when binding directly to a property of a class. Not much of an answer, I know, but I don't think there's really a way around it. My suggestion would be to either not directly inherit from Dictionary; rather keep an internal Dictionary, and expose methods as needed. OR, don't databind the texbox directly. Rather, raise an event whenever your "Desc" property changes in your RatesCache class, and then in your form listen to that event. When it changes, update your textbox.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM