问题描述
我有一个gridview,网格有5个不同的ID,FirstName,LastName,DateOfBirth和Age列,可以编辑gridview,所以我想根据DateOfBirth列更新Age,所以我在OnRowBound函数中编写了必要的功能。在网格视图页面上,我得到\“字符串未被识别为有效的日期时间\”。
这是OnRowBound的功能
protected void UserInfoGrid_RowDataBound(object sender,GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DaTarow)
{
DateTime dobOnGrid = DateTime.ParseExact(e.Row.Cells[3].Text,\"MM/dd/yyyy\",null);
Label tAge = (Label)e.Row.Cells[4].FindControl(\"txtAge\");
TimeSpan ts = DateTime.Now - dobOnGrid;
int CurrAge = ts.Days / 365;
tAge.Text = CurrAge.ToString();
}
}
<asp:GridView ID=\"UserInfoGrid\" runat=\"server\" AutoGenerateColumns=\"False\" CellPadding=\"3\"
DataKeyNames=\"userid\" DataSourceID=\"DataSrcUserInfo\"
AllowPaging=\"True\" OnRowDataBound=\"UserInfoGrid_RowDataBound\"
OnRowUpdated=\"Update\" OnRowDeleted=\"Delete\" PageSize=\"10\" >
谁能帮我这个
谢谢,
解决方法
首先,您显示的代码不应该在
RowUpdating
事件处理程序中吗?至于您得到的错误,显然是由于生日单元格中格式错误的字符串造成的。
您是否检查了空字符串?我猜想您甚至在RowDataBound
事件处理程序中将GridView
呈现在屏幕上之前就得到了异常,该事件处理程序在GridView加载时触发。