2016-08-05 28 views
0

DataGridViewの検索テキストをハイライトしたいと思います。私はsearchtextの境界を見つけてFillRectangleを描くためにcellFormattingイベントを試みましたが、検索テキストの境界を正確に取得できませんでした。追加画像で DataGridViewで検索テキストを強調表示する方法は?

enter image description here

は、私は、「o」は、テキストを強調しようとしたが、それはまた、他の文字を強調しています。

検索したテキストをハイライト表示するための四角形を描画する方法を教えてください。

よろしくお願いします。 Amal Raj。

+0

あなたのコードは何ですか? http://stackoverflow.com/questions/22322675/how-to-highlight-search-results-in-gridview-using-asp-net –

+0

私はWinFormsの技術を求めています。 – Amal

+0

グリッド方法でデータをバインドするときに、特定の条件を実行する必要があります。これは、これから何かを見つけることができます(http://stackoverflow.com/questions/10090691/add-progress-bar-in-gridview-using-datatable-or- dataset-in-window-application/10100992#10100992) –

答えて

2

CellPainitingイベントを使用する必要があります。このコードを試してみてください:

string keyValue = "Co"; //search text 

    private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) 
    { 
     if (e.Value == null) return; 

     StringFormat sf = StringFormat.GenericTypographic; 
     sf.FormatFlags = sf.FormatFlags | StringFormatFlags.MeasureTrailingSpaces | StringFormatFlags.DisplayFormatControl; 
     e.PaintBackground(e.CellBounds, true); 

     SolidBrush br = new SolidBrush(Color.White); 
     if (((int)e.State & (int)DataGridViewElementStates.Selected) == 0) 
      br.Color = Color.Black; 

     string text = e.Value.ToString(); 
     SizeF textSize = e.Graphics.MeasureString(text, Font, e.CellBounds.Width, sf); 

     int keyPos = text.IndexOf(keyValue, StringComparison.OrdinalIgnoreCase); 
     if (keyPos >= 0) 
     { 
      SizeF textMetricSize = new SizeF(0, 0); 
      if (keyPos >= 1) 
      { 
       string textMetric = text.Substring(0, keyPos); 
       textMetricSize = e.Graphics.MeasureString(textMetric, Font, e.CellBounds.Width, sf); 
      } 

      SizeF keySize = e.Graphics.MeasureString(text.Substring(keyPos, keyValue.Length), Font, e.CellBounds.Width, sf); 
      float left = e.CellBounds.Left + (keyPos <= 0 ? 0 : textMetricSize.Width) + 2; 
      RectangleF keyRect = new RectangleF(left, e.CellBounds.Top + 1, keySize.Width, e.CellBounds.Height - 2); 

      var fillBrush = new SolidBrush(Color.Yellow); 
      e.Graphics.FillRectangle(fillBrush, keyRect); 
      fillBrush.Dispose(); 
     } 
     e.Graphics.DrawString(text, Font, br, new PointF(e.CellBounds.Left + 2, e.CellBounds.Top + (e.CellBounds.Height - textSize.Height)/2), sf); 
     e.Handled = true; 

     br.Dispose(); 
    } 
+0

ソリューションは正常に動作します。しかし、WrapModeを設定したら、上記のフォーマットはwrapmodeを無効にします。ラップされたモードでは強調表示が機能していません。 – Amal

+0

しかし、私にとっては、セルのフォント/レイアウト/アライメントは他のセルとはまったく違うので、もっと見ていく必要があります。 –

関連する問題