开发者

ASP .Net Gridview bind to data only when clicking update

Here's how I want the control to work. Click edit on a row in gridview. There's a textbox in one of the columns, I would like it to be blank even though there's data in the database for that column, but when I click update I would like whateve开发者_如何学编程r new text the user entered to update the database for that column. It would be one-way databinding, but the other way?


Here's how I did it using an sql datasource with the select,update and delete methods generated.

First, you'll need to make any column that you want to edit like this a template field with an item template and and edit item template:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
        DataKeyNames="ID" DataSourceID="SqlDataSource1" 
        onrowupdating="GridView1_RowUpdating">
    <Columns>
    <asp:TemplateField HeaderText="City" SortExpression="City">
        <ItemTemplate>
           <asp:Label runat="server" Text='<%# Eval("City") %>'></asp:Label>
        </ItemTemplate>
        <EditItemTemplate>
           <asp:TextBox runat="server"  ID="txtCityEdit" Text=""></asp:TextBox>
        </EditItemTemplate>
     </asp:TemplateField>
     </Columns>
</asp:GridView>

Next handle the gridview's on update event:

    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        //find the value control who's value you want
        TextBox tb = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtCityEdit");

        //since we are not using a bound column for city we need to explicitly insert the value
        //into the update parameter.
        SqlDataSource1.UpdateParameters["City"].DefaultValue = tb.Text;
    }

Even if you are using something other than an SQL Datasource this should be the basic solution.


// Find notes textbox
TextBox tb = (TextBox)MyActiveReferrals.Rows[e.RowIndex].FindControl("NotesTextBox");
e.NewValues.Add("Notes", tb.Text);

I used a linq data source.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜