问题
I want to duplicate the same functionality of the edit button using a single click anywhere in a GridView row.
The code below does this, but with a major problem: if the user clicks off of one textbox to the next, the edit command fires again, and the changes made to the previous textbox revert back to it's original value.
Any suggestions on how to fix this behaviour?
Or, is there a better approach to accomplishing this?
EDIT: This was resolved by adding a check for row.RowState.HasFlag( DataControlRowState.Edit ). See code below:
protected override void Render( System.Web.UI.HtmlTextWriter writer )
{
foreach( GridViewRow row in gvwOrderItems.Rows )
{
if( row.RowType == DataControlRowType.DataRow &&
row.RowState.HasFlag( DataControlRowState.Edit ) == false )
{
// enable click on row to enter edit mode
row.Attributes["onclick"] =
ClientScript.GetPostBackClientHyperlink( gvwOrderItems, "Edit$" + row.DataItemIndex, true );
}
}
base.Render( writer );
}
回答1:
Check for row.RowState.HasFlag( DataControlRowState.Edit ).
protected override void Render( System.Web.UI.HtmlTextWriter writer )
{
foreach( GridViewRow row in gvwOrderItems.Rows )
{
if( row.RowType == DataControlRowType.DataRow &&
row.RowState.HasFlag( DataControlRowState.Edit ) == false )
{
// enable click on row to enter edit mode
row.Attributes["onclick"] =
ClientScript.GetPostBackClientHyperlink( gvwOrderItems, "Edit$" + row.DataItemIndex, true );
}
}
base.Render( writer );
}
回答2:
I didn't test this as I don't use GridView, but I do it with other controls. You should be able to put hidden button in the row and call Click on the row via JavaScript:
protected override void Render( System.Web.UI.HtmlTextWriter writer )
{
foreach( GridViewRow row in gvwOrderItems.Rows )
{
if( row.RowType == DataControlRowType.DataRow )
{
Button b = new Button();
b.ID = "whatever";
b.CommandName = "edit";
b.Attributes.Add("style","display:none;")
row.Controls.Add(b);
// enable click on row to enter edit mode
row.Attributes.Add("onclick" ,"document.getElementById('" bla.ClientID "').click();");
}
}
base.Render( writer );
}
来源:https://stackoverflow.com/questions/7262409/click-anywhere-on-a-gridview-row-to-enter-the-edit-mode