简体   繁体   中英

Define maximum for NumerictUpDown in a dictionary

So I have a dictionary with a few controls called controlDict . But if I want to set the maximum for a NumericUpDown control like this:

controlDict.Add("amountNum" + i.ToString(), new NumericUpDown());
            controlDict["amountNum" + i.ToString()].Location = new Point(60, 42);
controlDict["amountNum" + i.ToString()].Maximum = new decimal(new int[] {
            -1,
            -1,
            -1,
            0});

It gives me this error:

'Control' does not contain a definition for 'Maximum' and no extension method 'Maximum' accepting a first argument of type 'Control' could be found (are you missing a using directive or an assembly reference?)

How can I solve this?

You should cast the control to NumericUpDown then assign values to its properties:

var numeric = (NumericUpDown)controlDict["amountNum" + i.ToString()];
numeric.Maximum = 100;

Why controlDict["amountNum" + i.ToString()].Location works without casting?

Because the result is Control and the control class has Location property. And all of your controls including NumericUpDown inherited from Control .

Items of your dictionary are of type Control . When you get an item from your dictionary using controlDict["key"] the result is of type Control . So you can access all properties of Control class. When you know the result control is specific control type, to have access to the specific control properties you should cast it to specific control type.

This is because controlDict["amountNum" + i.ToString()] is Control instance. Try this:

(controlDict["amountNum" + i.ToString()] as NumericUpDown).Maximum = new decimal(new int[] {
        -1,
        -1,
        -1,
        0});

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