2

我有一个基本的网格视图,我将来自 SQL 存储过程的代码中的数据绑定到该网格视图。

<asp:GridView ID="gvCheckResults" runat="server" 
        OnRowDataBound="gvCheckResults_RowDataBound" 
        RowStyle-CssClass="gridViewRow" 
        CssClass="gridView"
        AlternatingRowStyle-CssClass="gridViewAlternatingRow" 
        HeaderStyle-CssClass="gridViewHeader">
    </asp:GridView> 

数据绑定:

gvCheckResults.DataSource = dataContext.GetResults(Name, Address);
gvCheckResults.DataBind();

if (!IsPostBack)
{
    //Add Edit column.
    CommandField cField = new CommandField();
    cField.EditText = "Edit";
    cField.ShowEditButton = true;
    gvCheckResults.Columns.Insert(0, cField);
}

如何以编程方式将编辑按钮添加到每个结果行?我知道在 aspx 页面中设置数据源对象时该怎么做,但从未以编程方式完成。

4

1 回答 1

6

像这样试试

<asp:TemplateField HeaderText="Edit>
    <ItemTemplate>
        <asp:LinkButton Id="lnkEdit" runat="server" CommandName="Edit" Text="Edit"/>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:LinkButton Id="lnkEdit" runat="server" CommandName="Update" Text="Update"/>
        <asp:LinkButton Id="LinkButton1" runat="server" CommandName="Cancel" Text="Cancel"/>
    </EditItemTemplate>
</asp:TemplateField>

OnRowEditEvent()像这样将gridview编辑索引设置为e.newrowindex并再次绑定它。

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
    GridView1.EditIndex = e.NewEditIndex;
    GridView1.DataBind();
}

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    //Write code TO UPDATE YOUR DATABESE THEN WRITE BELOW CODE IN LAST
    // To Find Text of TextBox to get updated value....you get it in string like this.
    //string strName = ((TextBox)grdview1.Rows[e.RowIndex].Cells[YourColumnIndexInWhichTexBoxAppear].Controls[0]).Text;
    GridView1.EditIndex = -1;
    GridView1.DataBind();
}

protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
    GridView1.EditIndex = -1;
    GridView1.DataBind();
}
于 2013-04-29T13:58:59.347 回答