gridview编辑模式以编程方式

时间:2013-04-29 13:55:09

标签: c# asp.net sql gridview

我有一个基本的gridview,我从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页面中设置数据源对象时这样做,但从未以编程方式完成。

1 个答案:

答案 0 :(得分:5)

尝试这样

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