ユーザーにデータ入力機能を表示する場合、フォームに入力されたデータを頻繁に検証する必要があります。 DataGridView クラスは、データがデータ ストアにコミットされる前に検証を実行する便利な方法を提供します。 現在のセルが変更されたときにCellValidatingによって発生するDataGridView イベントを処理することで、データを検証できます。
このチュートリアルでは、Northwind サンプル データベースの Customers
テーブルから行を取得し、 DataGridView コントロールに表示します。 ユーザーが CompanyName
列のセルを編集し、セルから離れようとすると、 CellValidating イベント ハンドラーは新しい会社名文字列を調べて空でないことを確認します。新しい値が空の文字列の場合、 DataGridView は空でない文字列が入力されるまで、ユーザーのカーソルがセルから離れることを防ぎます。
このトピックのコードを 1 つのリストとしてコピーするには、「 方法: Windows フォーム DataGridView コントロールでデータを検証する」を参照してください。
[前提条件]
このチュートリアルを完了するには、次のものが必要です。
- Northwind SQL Server サンプル データベースを持つサーバーへのアクセス。
フォームの作成
DataGridView に入力されたデータを検証するには
Formから派生し、DataGridView コントロールとBindingSource コンポーネントを含むクラスを作成します。
次のコード例では、基本的な初期化を提供し、
Main
メソッドを含みます。using System; using System.Data; using System.Data.SqlClient; using System.Windows.Forms; public class Form1 : System.Windows.Forms.Form { private DataGridView dataGridView1 = new DataGridView(); private BindingSource bindingSource1 = new BindingSource(); public Form1() { // Initialize the form. this.dataGridView1.Dock = DockStyle.Fill; this.Controls.Add(dataGridView1); this.Load += new EventHandler(Form1_Load); this.Text = "DataGridView validation demo (disallows empty CompanyName)"; }
Imports System.Data Imports System.Data.SqlClient Imports System.Windows.Forms Public Class Form1 Inherits System.Windows.Forms.Form Private WithEvents dataGridView1 As New DataGridView() Private bindingSource1 As New BindingSource() Public Sub New() ' Initialize the form. Me.dataGridView1.Dock = DockStyle.Fill Me.Controls.Add(dataGridView1) Me.Text = "DataGridView validation demo (disallows empty CompanyName)" End Sub
[STAThread] static void Main() { Application.EnableVisualStyles(); Application.Run(new Form1()); } }
<STAThread()> _ Shared Sub Main() Application.EnableVisualStyles() Application.Run(New Form1()) End Sub End Class
データベースへの接続の詳細を処理するためのメソッドをフォームのクラス定義に実装します。
このコード例では、設定された
GetData
オブジェクトを返すDataTable メソッドを使用します。connectionString
変数は、データベースに適した値に設定してください。重要
接続文字列内にパスワードなどの機密情報を格納すると、アプリケーションのセキュリティに影響する可能性があります。 統合セキュリティとも呼ばれる Windows 認証を使用すると、データベースへのアクセスをより安全に制御できます。 詳細については、「接続情報の保護」を参照してください。
private static DataTable GetData(string selectCommand) { string connectionString = "Integrated Security=SSPI;Persist Security Info=False;" + "Initial Catalog=Northwind;Data Source=localhost;Packet Size=4096"; // Connect to the database and fill a data table. SqlDataAdapter adapter = new SqlDataAdapter(selectCommand, connectionString); DataTable data = new DataTable(); data.Locale = System.Globalization.CultureInfo.InvariantCulture; adapter.Fill(data); return data; }
Private Shared Function GetData(ByVal selectCommand As String) As DataTable Dim connectionString As String = _ "Integrated Security=SSPI;Persist Security Info=False;" + _ "Initial Catalog=Northwind;Data Source=localhost;Packet Size=4096" ' Connect to the database and fill a data table. Dim adapter As New SqlDataAdapter(selectCommand, connectionString) Dim data As New DataTable() data.Locale = System.Globalization.CultureInfo.InvariantCulture adapter.Fill(data) Return data End Function
フォームのLoadイベントのハンドラーを実装して、DataGridViewとBindingSourceを初期化し、データバインディングを設定します。
private void Form1_Load(System.Object sender, System.EventArgs e) { // Attach DataGridView events to the corresponding event handlers. this.dataGridView1.CellValidating += new DataGridViewCellValidatingEventHandler(dataGridView1_CellValidating); this.dataGridView1.CellEndEdit += new DataGridViewCellEventHandler(dataGridView1_CellEndEdit); // Initialize the BindingSource and bind the DataGridView to it. bindingSource1.DataSource = GetData("select * from Customers"); this.dataGridView1.DataSource = bindingSource1; this.dataGridView1.AutoResizeColumns( DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader); }
Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Me.Load ' Initialize the BindingSource and bind the DataGridView to it. bindingSource1.DataSource = GetData("select * from Customers") Me.dataGridView1.DataSource = bindingSource1 Me.dataGridView1.AutoResizeColumns( _ DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader) End Sub
DataGridView コントロールのCellValidatingイベントとCellEndEdit イベントのハンドラーを実装します。
CellValidating イベント ハンドラーでは、
CompanyName
列のセルの値が空かどうかを判断します。 セル値の検証に失敗した場合は、Cancel クラスの System.Windows.Forms.DataGridViewCellValidatingEventArgs プロパティをtrue
に設定します。 これにより、 DataGridView コントロールはカーソルがセルから離れないようにします。 行の ErrorText プロパティを説明文字列に設定します。 これにより、エラー テキストを含むツールヒントを含むエラー アイコンが表示されます。 CellEndEdit イベント ハンドラーで、行の ErrorText プロパティを空の文字列に設定します。 CellEndEdit イベントは、セルが編集モードを終了した場合にのみ発生します。検証に失敗した場合は実行できません。private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) { string headerText = dataGridView1.Columns[e.ColumnIndex].HeaderText; // Abort validation if cell is not in the CompanyName column. if (!headerText.Equals("CompanyName")) return; // Confirm that the cell is not empty. if (string.IsNullOrEmpty(e.FormattedValue.ToString())) { dataGridView1.Rows[e.RowIndex].ErrorText = "Company Name must not be empty"; e.Cancel = true; } } void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e) { // Clear the row error in case the user presses ESC. dataGridView1.Rows[e.RowIndex].ErrorText = String.Empty; }
Private Sub dataGridView1_CellValidating(ByVal sender As Object, _ ByVal e As DataGridViewCellValidatingEventArgs) _ Handles dataGridView1.CellValidating Dim headerText As String = _ dataGridView1.Columns(e.ColumnIndex).HeaderText ' Abort validation if cell is not in the CompanyName column. If Not headerText.Equals("CompanyName") Then Return ' Confirm that the cell is not empty. If (String.IsNullOrEmpty(e.FormattedValue.ToString())) Then dataGridView1.Rows(e.RowIndex).ErrorText = _ "Company Name must not be empty" e.Cancel = True End If End Sub Private Sub dataGridView1_CellEndEdit(ByVal sender As Object, _ ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) _ Handles dataGridView1.CellEndEdit ' Clear the row error in case the user presses ESC. dataGridView1.Rows(e.RowIndex).ErrorText = String.Empty End Sub
アプリケーションのテスト
これで、フォームをテストして、期待どおりに動作することを確認できます。
フォームをテストするには
アプリケーションをコンパイルして実行する。
DataGridViewには
Customers
テーブルのデータが入力されて表示されます。CompanyName
列のセルをダブルクリックすると、値を編集できます。 すべての文字を削除し、TAB キーを押してセルを終了すると、 DataGridView によって終了できなくなります。 セルに空でない文字列を入力すると、 DataGridView コントロールを使用してセルを終了できます。
次のステップ
このアプリケーションは、DataGridView コントロールの機能の基本的な理解を提供します。 DataGridView コントロールの外観と動作は、いくつかの方法でカスタマイズできます。
枠線とヘッダーのスタイルを変更します。 詳細については、「方法: Windows フォーム DataGridView コントロールの罫線と枠線のスタイルを変更するを参照してください。
DataGridView コントロールへのユーザー入力を有効または制限します。 詳細については、「方法: Windows フォーム DataGridView コントロールので行の追加と削除を防止する」および「方法: Windows フォーム DataGridView コントロールで列を Read-Only する方法」を参照してください。
データベース関連のエラーについてユーザー入力を確認します。 詳細については、「 チュートリアル: Windows フォーム DataGridView コントロールのデータ入力中に発生するエラーの処理」を参照してください。
仮想モードを使用して非常に大きなデータ セットを処理します。 詳細については、「チュートリアル: Windows フォーム DataGridView コントロールでの仮想モードの実装」を参照してください。
セルの外観をカスタマイズします。 詳細については、「 方法: Windows フォーム DataGridView コントロールのセルの外観をカスタマイズ する 」および「方法: Windows フォーム DataGridView コントロールでフォントと色のスタイルを設定する」を参照してください。
こちらも参照ください
- DataGridView
- BindingSource
- Windows フォームのDataGridView コントロールにおけるデータ入力
- 方法: Windows フォーム DataGridView コントロール でデータを検証する
- チュートリアル: Windows フォーム DataGridView コントロール でのデータ入力中に発生するエラーの処理
- 接続情報の保護
.NET Desktop feedback