【问题标题】:c# Numericupdown to pass a value to an integerc# Numericupdown 将值传递给整数
【发布时间】:2015-11-19 21:46:59
【问题描述】:

我在将 numericupdown 值传递为整数时遇到问题。

private void button5_Click(object sender, EventArgs e)
{
    int count = numericUpDown1.Value;
    updateCount(count);
}

所以,我想要做的是将 numericupdown 值的值传递给一个名为 count 的整数,然后将该值传递给一个更新我数据库中表的方法。

我最近才开始编写 C#,似乎无法理解一些文档。

【问题讨论】:

  • 将值分配给 int 时遇到的错误消息或问题是什么
  • 嗨,我添加了它的截图。我真的很抱歉这个问题。我知道这可能很简单

标签: c# visual-studio integer numericupdown


【解决方案1】:

NumericUpDown.Value 返回小数,所以需要四舍五入转换为整数

使用这个,

int count = Convert.ToInt32(Math.Round(numericUpDown1.Value, 0));
updateCount(count);

如果你已经将Increment设置为整数(无小数点)数字,则可以直接转换为整数类型,否则转换前先四舍五入是安全的。

所以没有圆

int count = Convert.ToInt32(numericUpDown1.Value);
updateCount(count);

【讨论】:

  • 是的。你真棒。再次感谢。 :)
  • 我知道这是很久以前的事了,但Math.Floor 肯定比Math.Round 更好?
【解决方案2】:

问题是 NumericUpDown 控件的数值是 decimal 并且您想将其分配给整数类型。你应该做一个 TypeCast 来分配它。同样有一个 Convert 类,您可以像这样使用它

int count = Convert.ToInt32(numericUpDown1.Value);

【讨论】:

  • 谢谢。我会试试这个并尽快发表评论。
  • 嗨,现在我知道问题所在了。吸取教训先生,非常感谢。
【解决方案3】:

这就是它要做的:

Dim numericUpDown1 As Integer

【讨论】:

    【解决方案4】:

    int count = (int)numericUpDown1.Value;

    【讨论】:

    • 你真的应该添加一些解释为什么这个代码应该工作 - 你也可以在代码本身中添加 cmets - 在它的当前形式中,它没有提供任何可以帮助其余部分的解释社区了解您为解决/回答问题所做的工作。
    • 既然这样行不通,我也在搜索这方面的信息,因为这是我第一个想到但没有用的想法
    猜你喜欢
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多