我有以下代码
public class SpecialItemRow : DataRow
{
public SpecialItemRow(DataRowBuilder builder)
: base(builder)
{
CreatedDate = DateTime.Now.ToLongTimeString();
}
public string ItemName { get { return Convert.ToString(base["_ItemName"]); } set { base["_ItemName"] = value; _UpdateModifiedDate(); } }
public string Price { get { return Convert.ToString(base["_Price"]); } set { base["_Price"] = value; _UpdateModifiedDate(); } }
public string CreatedDate { get { return Convert.ToString(base["_CreatedDate"]); } set { base["_CreatedDate"] = value; _UpdateModifiedDate(); } }
public string ModifiedDate { get { return Convert.ToString(base["_ModifiedDate"]); } set { base["_ModifiedDate"] = value; } }
private void _UpdateModifiedDate()
{
ModifiedDate = DateTime.Now.ToLongTimeString();
}
}
尝试自动设置修改日期和创建日期。但事实证明那些不适合放的地方。是否有任何其他可覆盖的方法来设置这些值?感谢。
答案 0 :(得分:0)
使用OnRowChanged(或OnRowChanging)在DataTable
中执行此操作。例如,
public class SpecialItemTable : DataTable
{
protected override void OnRowChanged(DataRowChangeEventArgs e)
{
if (e.Action == DataRowAction.Add)
{
r.Row["CreatedDate"] = DateTime.Now;
}
else if (e.Action == DataRowAction.Change)
{
var time = DateTime.Now;
// Check to prevent the cascaded row change events
if ((time - (DateTime)e.Row["LastUpdated"]).TotalMilliseconds > 2)
{
e.Row["LastUpdated"] = time;
}
}
}
}
(免责声明:未经测试的代码 - 仅提供一个想法)