True DBGrid for WinForms
インクリメンタル検索

With True DBGrid, you can easily perform search either on the whole grid or just a specific column. Incremental search for a column in the grid, positions a grid to that row if a match is found. The incremental searching feature specifically uses the grid's KeyPress event and the grid's indexer to retrieve and compare data for the particular column.

インクリメンタルサーチを使用して列のエントリを検索するには、Timer コンポーネントをフォームに追加し、KeyPressおよびTickイベントを設定します。

Complete the following steps:

  1. Timerコンポーネントをツールボックスからフォームに追加します。
  2. TimerのIntervalプロパティを 1 秒に設定します。

    デザイナの場合

    プロパティウィンドウで Timer1Interval プロパティを見つけ、これを 1000 に設定します。

    コードの場合

    Form_Loadイベントに次のコードを追加します。

    C#
    コードのコピー
    this.timer1.Interval = 1000;
    
  3. KeyPressイベントを追加します。

    C#
    コードのコピー
    private void c1TrueDBGrid1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
            {
                // キーストロークを処理します。
                e.Handled = true;
                this._searchString += e.KeyChar;
                int count = this.c1TrueDBGrid1.Splits[0].Rows.Count;
                int start = this.c1TrueDBGrid1.Row;
                int current = (start + 1) % count;
                // 検索が開始位置に戻ったら停止します。
                while( current != start )
                {
                    // 値を取得します。
                    string s = this.c1TrueDBGrid1[current, this.c1TrueDBGrid1.Col].ToString();
                    // 一致が見つかったら、終了します。
                    if(!string.IsNullOrEmpty(s) && s.Length >= _searchString.Length && s.Substring(0, _searchString.Length).ToUpper() == _searchString.ToUpper() )
                        break;
                    // 次の行を検索し、必要に応じて列を折り返します。
                    current = (current + 1) % count;
                }
                // グリッドの現在行を更新します。
                this.c1TrueDBGrid1.Row = current;
                // エントリを強調表示します。
                this.timer1.Enabled = true;
            }
    
  4. タイマーに Tickイベントを追加します。

    C#
    コードのコピー
    private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
            {
                this._searchString = string.Empty;
                this.timer1.Enabled = false;
            }
    

ユーザーが入力を行うと、その文字を含むセルが検索されて強調表示されます。この例では、Last 列で「V」を入力すると、「Varese」が強調表示されます。

注意:1 秒後に、検索文字列はリセットされます。