2016-11-03 102 views
1

我需要顯示一個佔位符,該佔位符在Winforms中的第一行數據網格視圖的前兩列中包含一個字符串。當數據網格爲空時,將顯示佔位符。在DataGridView單元格中顯示佔位符文本

enter image description here

+0

你真的是一個Label控件?或者你只是想設置兩個單元格的文本值? – TaW

+0

其實我試圖把標籤作爲佔位符放在那些cells.so,如果datagridview是空的,我可以在那些單元上顯示它。 – biff

+0

請根據您的新評論更改問題標題和說明。你想繪製前2列的佔位符文本。此外,您似乎不需要單擊按鈕,只需在單元格爲空時在單元格上顯示它們。 –

回答

2

您需要處理CellPainting事件和借鑑的地方持有者自己:

void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) 
{ 
    if (e.RowIndex < 0 || e.ColumnIndex < 0)  /*If a header cell*/ 
     return; 
    if (!(e.ColumnIndex == 0 || e.ColumnIndex == 1) /*If not our desired columns*/ 
     return; 

    if(e.Value == null || e.Value == DBNull.Value) /*If value is null*/ 
    { 
     e.Paint(e.CellBounds, DataGridViewPaintParts.All 
      & ~(DataGridViewPaintParts.ContentForeground)); 

     TextRenderer.DrawText(e.Graphics, "Enter a value", e.CellStyle.Font, 
      e.CellBounds, SystemColors.GrayText, TextFormatFlags.Left); 

     e.Handled = true; 
    } 
} 
+0

這是正確的。 –

+0

非常感謝您的幫助。 – biff

0

所以,你可以提高這個(爲Textbox工作),並更改dataGrid.Text

Textbox myTxtbx = new Textbox(); 
myTxtbx.Text = "Enter text here..."; 

myTxtbx.GotFocus += GotFocus.EventHandle(RemoveText); 
myTxtbx.LostFocus += LostFocus.EventHandle(AddText); 

public void RemoveText(object sender, EventArgs e) 
{ 
    if (myTxtbx.Text == "Enter text here...") { 
     myTxtbx.Text = ""; 
    } 
} 

public void AddText(object sender, EventArgs e) 
{ 
    if(String.IsNullOrWhiteSpace(myTxtbx.Text)) 
     myTxtbx.Text = "Enter text here..."; 
} 

注:myTxtbx.Text = "Enter text here...";if (myTxtbx.Text == "Enter text here...")字符串「在這裏輸入文字... 「必須相等。

+0

** 1)**在進入編輯模式之前沒有'TextBox'。 ** 2)**您不應該將文本分配給'TextBox'。你應該畫的地方持有人 –

+0

我的答案不是最好的,但我寫了一個用法的想法。 –

相關問題