我使用的是SQL Server 2005和Visual Studio 2008,C#。
在数据源(SQL Server数据表)中,我使用 DateTime 格式 mm / dd / yyyy ,但是,在表单概述(DataGridView)中,用户会喜欢看到完全其他格式,包括年份,周数和星期数( yyww,d ),格式为字符串。 我创建了一个用于值之间转换的算法(日期到工作日),但是我可以使用yyww,d(字符串)而不是mm / dd / yyyy(DateTime)填充受影响的单元格吗?
这是我一直在测试的,没有成功 (请注意,最后一行问题变得明显,因为单元格值在运行时不接受字符串 - 它仍然希望是 DateTime ...)
private void DataGridViewQueryFindRequests_CellFormatting(
object sender, DataGridViewCellFormattingEventArgs e)
{
string weekAndDay = "";
DataGridViewCell cell =
DataGridViewQueryFindRequests.Rows[e.RowIndex].Cells[e.ColumnIndex];
if (cell.ColumnIndex == 13 && cell.Value == null)
mEmptyRow = true;
if ((cell.ColumnIndex == 14 || cell.ColumnIndex == 15) && !mEmptyRow)
{
weekAndDay = ClassWeeksAndDates.dateToWeekNumber(Convert.ToDateTime(cell.Value));
cell.ValueType = typeof(string);
cell.Value = weekAndDay;
}
}
答案 0 :(得分:0)
几天前我遇到了类似的问题。
尽量不要更改ValueType
事件中的CellFormatting
,而只更改Value
。{/ p>
为避免在运行时收到FormatException
,您必须在要将其存储回来时转换/解析该值
您可以在CellParsing
事件中进行此操作,然后您可以将您想要的可见格式 yyww,d 转换为可接受的DateTime格式 mm / dd / yyyy
也许看看这个答案可能有所帮助:DataGridView Cell Editing issue with decimal/hexadecimal formatting