开发者

Using SqlDataAdapter.Update and RowUpdating to update a database from a gridview

开发者 https://www.devze.com 2023-01-27 01:19 出处:网络
I am posting this question after reading other similar questions about my problem but not really understanding how I can use the information.

I am posting this question after reading other similar questions about my problem but not really understanding how I can use the information.

I have been mainly writing this code to see how I can use SqlDataAdapters to update a database from a GridView.

I am writing my GridView in my aspx page as follows:

<asp:GridView ID="Clients" runat="server">
    <Columns>
        <asp:TemplateField HeaderText="Name" SortExpression="Name">
            <ItemTemplate>
             开发者_开发技巧   <asp:Label ID="labelName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="textboxName" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>
            </EditItemTemplate>
        </asp:TemplateField>
        <asp:CommandField EditText="Edit" ShowEditButton="true" />
    </Columns>
</asp:GridView>

Then in my code behind file I am writing the following code (Database is just a class to connect to my database...):

Database database = new Database();
database.open_connection();

SqlCommand command = new SqlCommand(query, database.dbConnection);
SqlDataAdapter adapter = new SqlDataAdapter(command);

DataTable dataTable = new DataTable();
adapter.Fill(dataTable);

SqlCommandBuilder builder = new SqlCommandBuilder(adapter);

Clients.AutoGenerateColumns = false;
Clients.PageIndexChanging += new GridViewPageEventHandler(this.grid_view_page_index_changing);
Clients.Sorting += new GridViewSortEventHandler(this.grid_view_sorting);
Clients.RowEditing += new GridViewEditEventHandler(this.row_editing);
Clients.RowUpdating += new GridViewUpdateEventHandler(this.row_updating);
Clients.RowCancelingEdit += new GridViewCancelEditEventHandler(this.row_canceling_edit);
Clients.AllowPaging = true;
Clients.PageSize = 25;
Clients.AllowSorting = true;
Clients.DataSource = dataTable;
Clients.DataBind();

database.close_connection();

This all works fine so far; The GridView Sorting, Editing, RowCancellingEdit, PageIndexChanging functions etc work as they should do.

My problem is when I call the RowUpdating function.

What I want to do is use the adapter.Update() function to update the database.

It doesn't throw any errors with my current code, but it doesn't update the database either.

As soon as I click update, the edit text box from my GridView disappears and I am left with the original value before trying to edit it.

This is my row_updating() function:

public void row_updating(object sender, GridViewUpdateEventArgs e) {
    GridViewRow gvr = gridView.Rows[Clients.EditIndex];

    TextBox txt = (TextBox)gvr.Cells[0].FindControl("textboxName");
    e.NewValues["Name"] = txt.Text;

    adapter.Update((DataTable)Clients.DataSource);

    Clients.EditIndex = -1;
    Clients.DataBind();
}

I can't figure out why it won't update the database (Probably because I am doing it completely wrong)

I have seen stuff around the internet that mentions a EndEdit() function, but I'm not sure if that applies here.

If anyone could tell me what I am doing wrong and why my database won't update it would be much appreciated.


Have you created the UpdateCommand for your data adapter. If not then I think you may need to do it to successfully update the data.

Also check this MSDN link:

If INSERT, UPDATE, or DELETE statements have not been specified, the Update method generates an exception. However, you can create a SqlCommandBuilder or OleDbCommandBuilder object to automatically generate SQL statements for single-table updates if you set the SelectCommand property of a .NET Framework data provider. Then, any additional SQL statements that you do not set are generated by the CommandBuilder. This generation logic requires key column information to be present in the DataSet. For more information see Generating Commands with CommandBuilders (ADO.NET).

The Update method retrieves rows from the table listed in the first mapping before performing an update. The Update then refreshes the row using the value of the UpdatedRowSource property. Any additional rows returned are ignored.

After any data is loaded back into the DataSet, the OnRowUpdated event is raised, allowing the user to inspect the reconciled DataSet row and any output parameters returned by the command. After a row updates successfully, the changes to that row are accepted.

When using Update, the order of execution is as follows:

The values in the DataRow are moved to the parameter values.

The OnRowUpdating event is raised.

The command executes.

If the command is set to FirstReturnedRecord, then the first

returned result is placed in the DataRow.

If there are output parameters, they are placed in the DataRow.

The OnRowUpdated event is raised.

AcceptChanges is called.


I changed my row_updating() functions code which isn't of much relevence here, but the thing that fixed it for me was making sure I used !Page.IsPostBack

So now my Page_Load() functions sets up the GridView and then instead of just binding the data it goes:

if(!Page.IsPostBack) {
    Clients.DataBind();
}

Although it isn't working perfectly, at least it is now updating my database (Which is what this question was about, so I will post a new questions if I can't find a solution to my new problem)

Sometimes it's just the simplest things that cause the most frustrating problems...

0

精彩评论

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