我有一个由一组对象填充的datagridview。
第一列中的值类似于:
“ SOMEDISPLAYTEXT#T:\ blasndw \ lwwdjawn \ wjnawdja”
“ somedisplaytext#T:\ kndwla \ igrhysbv \ kjnfak”
我不希望更改这些值,因为我也在不断更新它们,但是,我希望datagridview仅显示此字符串“ somedisplaytext”的第一部分,直到但不包括“#”。改变基础价值。
最佳答案
如果您使用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;
}
}
}
关于c# - C#自定义格式设置datagridview列的显示数据而无需更改基础值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8853276/