ASP.NET Configure update button in GridView

2019-08-01 05:12发布

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: enter image description here

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

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.

enter image description here 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.

4条回答
够拽才男人
2楼-- · 2019-08-01 05:49

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.

查看更多
我只想做你的唯一
3楼-- · 2019-08-01 05:50
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>
查看更多
成全新的幸福
4楼-- · 2019-08-01 05:53

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...

查看更多
三岁会撩人
5楼-- · 2019-08-01 05:54

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".

查看更多
登录 后发表回答