ASP.NET Configure update button in GridView

有些话、适合烂在心里 提交于 2020-01-15 12:39:05

问题


I am using C# ASP.NET on VS2005.

I have a gridview table but it does not have a selection for Enable Editing when I right click on the Smart Tab.

Thus I manually added the edit button with the following code:

AutoGenerateEditButton="True"

The edit button has successfully appeared on my gridview like this:

When I click on the Edit button, the page is refreshed and the row is now editable:

However, when I pressed on the update button, I was brought to the error:

Updating is not supported by data source 'SqlDataSource1' unless UpdateCommand is specified.

http://i.stack.imgur.com/W97K0.png

I have no clue on how I can input or configure the UpdateCommand because I don't see any background code for the Update button.

Need help from experienced. Thank you in advance.


Edited: Added INSERT query in SqlDataSource1, however I still met the same error when I press the Update button.


回答1:


You need to re-configure the SqlDataSource1 control though which you can add support for INSERT, DELETE, UPDATE along with SELECT.

Take a look at this tutorial.




回答2:


while configurting sqldatasource when you configure the select statement for the gridview,there is a option as "advanced".click on that and then click on 'generate update,insert nad delete statements".




回答3:


For example, try this out...

  1. Firstly create a method to handle the update record.

    private void UpdateOrAddNewRecord(string parametervalue1, string parametervalue2)
        {
            using (openconn())
            {
                string sqlStatement = string.Empty;
                sqlStatement = "Update TableName set Name1 =@Name1 where Name2@Name2";
    
    
                try
                {
                //  SqlCommand cmd = new SqlCommand("storedprocedureName", con);
                  //cmd.CommandType = CommandType.StoredProcedure;
    
                    SqlCommand cmd = new SqlCommand(sqlStatement, con);
                    cmd.Parameters.AddWithValue("Name2", parametervalue2);
                    cmd.Parameters.AddWithValue("@Name1",parametervalue1);
    
                    cmd.CommandType = CommandType.Text;
                    cmd.ExecuteNonQuery();
    
                }
    
    
                catch (System.Data.SqlClient.SqlException ex)
                {
    
                    string msg = "Insert/Update Error:";
    
                    msg += ex.Message;
    
                    throw new Exception(msg);
    
    
                }
    
                finally
                {
    
                    closeconn();
    
                }
            }   
    
  2. Now create the row updating method..

    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            string ParameterValue1 = ((TextBox)GridView1.Rows[e.RowIndex].Cells[0].Controls[0]).Text;
    
            string ParameterValue2 = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text; //Name
    
            UpdateOrAddNewRecord(ParameterValue1, ParameterValue2); // call update method
    
            GridView1.EditIndex = -1;
            BindGridView();
            Label2.Visible = true;
            Label2.Text = "Row Updated";
        }
    
  3. Create Row Cancelling event..

    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { GridView1.EditIndex = -1; //swicth back to default mode BindGridView(); }

  4. Create row editing...

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

There are so many other way out to do this same activity in different fashion. This is most elementary way. Anyways if you find it useful, please mark it as your answer else let me know...




回答4:


In your code I think you have not handled the event for "Update".


Have a look at the below example hope it might help you,
check for the "UpdateCommand".
Also write a Update event in C# to update.



<asp:DetailsView ID="ManageProducts" runat="server" AllowPaging="True"
    AutoGenerateRows="False" DataKeyNames="ProductID"
    DataSourceID="ManageProductsDataSource" EnableViewState="False">
    <Fields>
        <asp:BoundField DataField="ProductID" HeaderText="ProductID"
            InsertVisible="False" ReadOnly="True" SortExpression="ProductID" />
        <asp:BoundField DataField="ProductName" HeaderText="ProductName"
            SortExpression="ProductName" />
        <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice"
            SortExpression="UnitPrice" />
        <asp:CheckBoxField DataField="Discontinued" HeaderText="Discontinued"
            SortExpression="Discontinued" />
    </Fields>
</asp:DetailsView>
<asp:SqlDataSource ID="ManageProductsDataSource" runat="server"
    ConnectionString="<%$ ConnectionStrings:NORTHWNDConnectionString %>"
    DeleteCommand=
        "DELETE FROM [Products] WHERE [ProductID] = @ProductID"
    InsertCommand=
        "INSERT INTO [Products] ([ProductName], [UnitPrice], [Discontinued])
         VALUES (@ProductName, @UnitPrice, @Discontinued)"
    SelectCommand=
        "SELECT [ProductID], [ProductName], [UnitPrice], [Discontinued]
         FROM [Products]"
    UpdateCommand=
        "UPDATE [Products] SET [ProductName] = @ProductName,
         [UnitPrice] = @UnitPrice, [Discontinued] = @Discontinued
         WHERE [ProductID] = @ProductID">
    <DeleteParameters>
        <asp:Parameter Name="ProductID" Type="Int32" />
    </DeleteParameters>
    <UpdateParameters>
        <asp:Parameter Name="ProductName" Type="String" />
        <asp:Parameter Name="UnitPrice" Type="Decimal" />
        <asp:Parameter Name="Discontinued" Type="Boolean" />
        <asp:Parameter Name="ProductID" Type="Int32" />
    </UpdateParameters>
    <InsertParameters>
        <asp:Parameter Name="ProductName" Type="String" />
        <asp:Parameter Name="UnitPrice" Type="Decimal" />
        <asp:Parameter Name="Discontinued" Type="Boolean" />
    </InsertParameters>
</asp:SqlDataSource>


来源:https://stackoverflow.com/questions/8264670/asp-net-configure-update-button-in-gridview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!