C# Windows Formsにおけるイベントハンドラの実装方法

イベントハンドラの自動生成

Windows Formsアプリケーションでは、コントロールをダブルクリックすることでVisual Studioが自動的にイベントハンドラを生成します。コントロールのNameプロパティに基づいて、対応するメソッドが作成されます。

using System;
using System.Windows.Forms;

namespace SampleApp
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void submitButton_Click(object sender, EventArgs e)
        {
            // イベント処理ロジックをここに記述
        }
    }
}

コントロール値の取得と検証

以下の例では、フォーム上の各コントロールから値を取得し、入力検証を行う方法を示します。

using System;
using System.Data;
using System.Windows.Forms;

namespace SampleApp
{
    public partial class MainForm : Form
    {
        private void ToggleInputFields(bool isVisible)
        {
            lineIdLabel.Visible = isVisible;
            deviceLabel.Visible = isVisible;
            lineIdTextBox.Visible = isVisible;
            deviceNameTextBox.Visible = isVisible;
        }

        public MainForm()
        {
            InitializeComponent();
            ToggleInputFields(false);
        }

        private void searchButton_Click(object sender, EventArgs e)
        {
            var startTime = startTimePicker.Value;
            var endTime = endTimePicker.Value;
            
            var lineIdentifier = lineIdTextBox.Text.Trim();
            var deviceIdentifier = deviceNameTextBox.Text.Trim();
            var dataSourceName = dataSourceComboBox.Text.Trim();

            if (string.IsNullOrEmpty(dataSourceName))
            {
                MessageBox.Show("データソースを選択してください。", "入力エラー");
                return;
            }

            if (weeklyReportRadio.Checked || dailyReportRadio.Checked)
            {
                if (weeklyReportRadio.Checked)
                {
                    if (string.IsNullOrEmpty(lineIdentifier) || string.IsNullOrEmpty(deviceIdentifier))
                    {
                        MessageBox.Show("ラインIDまたはデバイス名を入力してください。", "入力エラー");
                        return;
                    }
                }

                var queryResults = DatabaseManager.ExecuteQuery(
                    dataSourceName, 
                    startTime, 
                    endTime, 
                    weeklyReportRadio.Checked, 
                    dailyReportRadio.Checked,
                    lineIdentifier, 
                    deviceIdentifier
                );

                if (queryResults == null)
                {
                    MessageBox.Show("データ取得に失敗しました。", "エラー");
                    return;
                }

                resultsDataGrid.DataSource = queryResults;
            }
            else
            {
                MessageBox.Show("レポートタイプを選択してください。", "選択エラー");
            }
        }

        private void testConnectionButton_Click(object sender, EventArgs e)
        {
            var connectionString = connectionTextBox.Text.Trim();
            try
            {
                var connectionStatus = DatabaseManager.TestConnection(connectionString);
                statusLabel.Text = connectionStatus ? "接続成功" : "接続失敗";
            }
            catch (Exception ex)
            {
                statusLabel.Text = "接続エラー: " + ex.Message;
            }
        }

        private void weeklyReportRadio_CheckedChanged(object sender, EventArgs e)
        {
            ToggleInputFields(true);
            lineIdTextBox.Enabled = true;
            deviceNameTextBox.Enabled = true;
            lineIdTextBox.Focus();
        }

        private void dailyReportRadio_CheckedChanged(object sender, EventArgs e)
        {
            ToggleInputFields(false);
            lineIdTextBox.Enabled = false;
            deviceNameTextBox.Enabled = false;
        }

        private void exportButton_Click(object sender, EventArgs e)
        {
            try
            {
                ExportManager.ExportToExcel(resultsDataGrid);
                MessageBox.Show("エクスポートが完了しました。", "成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show("エクスポート失敗: " + ex.Message, "エラー");
            }
        }
    }
}

タグ: C# Windows Forms イベントハンドラ データ検証 UIコントロール

8月27日 08:32 投稿