我在aspx页面中使用了sqldatasource的detailsview。我正在尝试对某些字段进行一些预处理和后处理 - 基本上是将html列表转换为换行符分隔列表进行编辑,然后返回到html以存储在数据库中。
ItemUpdating中的后处理很简单,但DataBound中的预处理很麻烦......
protected void DetailsView1_DataBound(object sender, EventArgs e)
{
if (DetailsView1.Rows.Count > 2)
{
string s =((DataRowView)DetailsView1.DataItem).Row.ItemArray[2].ToString();
TextBox box1 = (TextBox) DetailsView1.FindControl("textbox1");
if (box1 != null)
{
box1.Text = preprocess(s);
}
}
}
它的脆弱性
string s=((DataRowView)DetailsView1.DataItem).Row.ItemArray[2].ToString();
这让我心烦意乱。我确信我遗漏了一些东西(不止一件事)!
我想我希望做更像我的ItemUpdating的事情......
e.NewValues["threeline"] = postprocess(e.NewValues["threeline"].ToString());
切换到Asp.Net 4.0+并使用ObjectDataSource
。
将ObjectDataSource.TypeName
设置为数据访问对象Type.FullName
。
将ObjectDataSource.DataObjectTypeName
设置为DTO Type.FullName
。
将ObjectDataSource.SelectMethod
设置为获取IQueryable<MyDto>
的数据访问对象方法。将DetailsView1.DataSourceID
设为ObjectDataSource.ID
。
将DetailsView1.ItemType
设置为DTO Type.FullName
。
并做这样的事情:
var item = DetailsView1.DataItem as MyDTO;
if(item == null)
return;
var box1 = (TextBox) DetailsView1.FindControl("textbox1");
if (box1 == null)
return;
box1.Text = preprocess(item.PropertyName);