2012-01-13 17 views
2

我有一個datagridview被一組對象填充。 第一列內的值是類似於:C#自定義格式化datagridview列的顯示數據而不更改基礎值

「SOMEDISPLAYTEXT#T:\ blasndw \ lwwdjawn \ wjnawdja」

「somedisplaytext#T:\ kndwla \ igrhysbv \ kjnfak」

我不希望更改這些值,因爲我也在不斷更新它們,但是,我希望datagridview只顯示此字符串'somedisplaytext'的第一部分,但不包括'#'..而不改變基礎值。

+0

只是爲了檢查的Value屬性,你在asp.net這樣做呢? – 2012-01-13 15:57:22

回答

3

如果您使用的WinForms:

根據MSDN(http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellformatting.aspx),你可以處理的CellFormating事件一個DataGridView,然後改變這個值的格式。

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 
{ 
    // If the column is the Artist column, check the 
    // value. 
    if (this.dataGridView1.Columns[e.ColumnIndex].Name == "Artist") 
    { 
     if (e.Value != null) 
     { 
      // Check for the string "pink" in the cell. 
      string stringValue = (string)e.Value; 
      stringValue = stringValue.ToLower(); 
      if ((stringValue.IndexOf("pink") > -1)) 
      { 
       e.CellStyle.BackColor = Color.Pink; 
      } 

     } 
    } 
    else if (this.dataGridView1.Columns[e.ColumnIndex].Name == "Release Date") 
    { 
     ShortFormDateFormat(e); 
    } 
} 

這第一種方法會改變背景顏色如果列藝術家包含「粉」,而且將改變在列「發佈日期」的值的格式與下面的方法:

你可以看到這裏,你只需要更換DataGridViewCellFormattingEventArgs

//Even though the date internaly stores the year as YYYY, using formatting, the 
//UI can have the format in YY. 
private static void ShortFormDateFormat(DataGridViewCellFormattingEventArgs formatting) 
{ 
    if (formatting.Value != null) 
    { 
     try 
     { 
      System.Text.StringBuilder dateString = new System.Text.StringBuilder(); 
      DateTime theDate = DateTime.Parse(formatting.Value.ToString()); 

      dateString.Append(theDate.Month); 
      dateString.Append("/"); 
      dateString.Append(theDate.Day); 
      dateString.Append("/"); 
      dateString.Append(theDate.Year.ToString().Substring(2)); 
      formatting.Value = dateString.ToString(); 
      formatting.FormattingApplied = true; 
     } 
     catch (FormatException) 
     { 
      // Set to false in case there are other handlers interested trying to 
      // format this DataGridViewCellFormattingEventArgs instance. 
      formatting.FormattingApplied = false; 
     } 
    } 
} 
1

的一種方法是建立在你的類中的屬性,它返回格式化文本

public PropertyForDisplay 
{ 
    get 
    { 
     String[] array = OriginalProperty.Split('#'); 
     if(array.Length > 0) 
      return array[0] ; 

     return String.Empty; 
    } 
} 
+3

如果不清楚,這個想法是將此屬性綁定到網格列,但不是原始屬性。當然,這將是一個只讀列。 – 2012-01-13 16:07:23

相關問題