我有一个datagridview被一组对象填充。 第一列中的值类似于:
“SOMEDISPLAYTEXT#T:\ blasndw \ lwwdjawn \ wjnawdja”
“somedisplaytext#T:\ kndwla \ igrhysbv \ kjnfak”
我不希望更改这些值,因为我也在不断更新它们,但是,我希望datagridview只显示此字符串'somedisplaytext'的第一部分,但不包括'#' ..没有改变基础价值。
答案 0 :(得分:3)
如果您使用WinForms:
根据MSDN(http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellformatting.aspx),您可以处理DataGridView的CellFormating事件,然后更改值的格式化方式。
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的Value属性
//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 :(得分:1)
一种方法是在类中创建一个返回格式化Text
的属性public PropertyForDisplay
{
get
{
String[] array = OriginalProperty.Split('#');
if(array.Length > 0)
return array[0] ;
return String.Empty;
}
}