views:

36

answers:

2

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 whatever new text the user entered to update the database for that column. It would be one-way databinding, but the other way?

A: 

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.

cptScarlet
That didn't work exactly for me, but definitely got me on the right track! My biggest problem was getting the value of the textbox out of the template field since intellisense wouldn't give it to me.I tried using the UpdateParameters like your example, but got a null reference error, then I tried adding my new one to the collection and that didn't work either.I ended up added my new value to the "NewValues" collection and it worked.
A: 
// Find notes textbox
TextBox tb = (TextBox)MyActiveReferrals.Rows[e.RowIndex].FindControl("NotesTextBox");
e.NewValues.Add("Notes", tb.Text);

I used a linq data source.