how to modify data in a DetailsView Databound even

2019-08-12 19:49发布

问题:

I'm using a detailsview with an sqldatasource in the aspx page. I'm trying to do some pre and post processing on some of the fields - basically to convert a html list to a newline separated list for editing and back to html to store in the database.

The post-processing in ItemUpdating is easy enough but the pre-processing in DataBound is messy...

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);
        }
    }
}

Its the fragility of

string s=((DataRowView)DetailsView1.DataItem).Row.ItemArray[2].ToString();

that upsets me. I'm sure I am missing something (more than one thing) obvious!

I guess I was hoping to do something more like my ItemUpdating...

e.NewValues["threeline"] = postprocess(e.NewValues["threeline"].ToString());

回答1:

Switch to Asp.Net 4.0+ and use ObjectDataSource.

Set ObjectDataSource.TypeName to the data access object Type.FullName.
Set ObjectDataSource.DataObjectTypeName to the DTO Type.FullName.
Set ObjectDataSource.SelectMethod to the data access object method that get a IQueryable<MyDto>. Set DetailsView1.DataSourceID to ObjectDataSource.ID.
Set DetailsView1.ItemType to the DTO Type.FullName.

And does somthing like this:

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);