0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C# - NumericUpDownのサンプル コードべた書き(Visual Studio不使用)

Last updated at Posted at 2020-10-26

目次: C# - Windows Formsでよく使うコントロールたち (Visual Studioなし環境向け) - Qiita

画面キャプチャ

image.png

テンプレ


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

class NumericUpDownSample : Form
{
    NumericUpDown nud;

    NumericUpDownSample()
    {
        ClientSize = new Size(300, 100);
        
        Controls.Add(nud = new NumericUpDown(){
            Location = new Point(0, 0),
            Width = 80,
            Maximum = 20,
            Minimum = 0,
            Value = 5,
        });

        nud.ValueChanged += Nud_ValueChanged;
    }

    void Nud_ValueChanged(object sender, EventArgs e)
    {
        int n = (int)nud.Value; // NumericUpDownのValueプロパティはdecimal型なので、整数にしたい場合は、キャストが必要

        int prod = 1;
        // checked {}で囲むと、オーバーフローを検出したときにエラーを発生させる。
        // ※13の階乗(13!)は C#の intの最大値 (2^31)-1 を超えてオーバーフローする
        checked {
            for ( int k=1; k<=n; k++ ) {
                prod *= k;
            }
        }

        Text = n.ToString()+"! = " + prod.ToString();
    }

    [STAThread]
    static void Main()
    {
        Application.Run(new NumericUpDownSample());
    }
}

ついでにオーバーフロー仕込んでみた・・・1

参考サイト

  1. decimal型のまま計算すればもうちょい行けるけど、論点がずれすぎるのと、精度とかややこしくなりそうなのでやめておく

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?