简体   繁体   English

在字典中为NumerictUpDown定义最大值

[英]Define maximum for NumerictUpDown in a dictionary

So I have a dictionary with a few controls called controlDict . 所以我有一本字典,里面有一些叫做controlDict控件。 But if I want to set the maximum for a NumericUpDown control like this: 但是,如果我想像这样设置NumericUpDown控件的最大值:

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?) “控件”不包含“最大”的定义,找不到可以接受类型为“控件”的第一个参数的扩展方法“最大”(您是否缺少using指令或程序集引用?)

How can I solve this? 我该如何解决?

You should cast the control to NumericUpDown then assign values to its properties: 您应该将控件转换为NumericUpDown然后为其属性分配值:

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

Why controlDict["amountNum" + i.ToString()].Location works without casting? 为什么controlDict["amountNum" + i.ToString()].Location无需转换即可工作?

Because the result is Control and the control class has Location property. 因为结果是Control ,并且控件类具有Location属性。 And all of your controls including NumericUpDown inherited from Control . 以及所有控件,包括从Control继承的NumericUpDown

Items of your dictionary are of type Control . 字典中的项目属于Control类型。 When you get an item from your dictionary using controlDict["key"] the result is of type Control . 当您使用controlDict["key"]从字典中获取一项时,结果为Control类型。 So you can access all properties of Control class. 因此,您可以访问Control类的所有属性。 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. 这是因为controlDict [“ amountNum” + i.ToString()]是Control实例。 Try this: 尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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