0

バックエンドで gridview 行を削除しようとしています。クリックdeleteすると から削除されgridviewますが、データベースからは削除されません。これがなぜなのか誰にもわかりますか?私のコードは次のとおりです。

protected void GVMyBookings_DeleteBooking(object sender, GridViewDeleteEventArgs e)
{
     string connstring = ConfigurationManager.ConnectionStrings["BookingConn"].ToString();
     SqlConnection MyConnection = new SqlConnection(connstring);

     MyConnection.Open();

     SqlDataSource SDSBooking= new SqlDataSource();
     SDSBooking.DeleteCommand = "DELETE FROM Tbl_Booking WHERE BookingID_PK = @BookingID_PK";
     SDSBooking.DeleteParameters.Add("@BookingID_PK", GVMyBookings.Rows[e.RowIndex].Cells[0].ToString());
     SDSBooking.ConnectionString = connstring;

     GVMyBookings.DataSource = SDSBooking;
     GVMyBookings.DataBind();
     MyConnection.Close();
}

グリッドビューは次のとおりです。

<asp:GridView ID="GVMyBookings" runat="server" GridLines="Vertical" AllowSorting="True"
    AutoGenerateColumns="False" AutoGenerateDeleteButton="true" 
    OnRowDeleting="GVMyBookings_DeleteBooking" EmptyDataText="You have no upcoming bookings" >
    <RowStyle BackColor="#e5ecbf" />
    <Columns>
        <asp:BoundField DataField="BookingID_PK"  />
        <asp:BoundField DataField="BookingDate" HeaderText="Booking Date" 
            SortExpression="BookingDate" DataFormatString="{0:d}" />
        <asp:BoundField DataField="RoomName" HeaderText="Room Name" 
            SortExpression="RoomName" />
        <asp:BoundField DataField="StartTime" HeaderText="Start Time" 
            SortExpression="StartTime"/>
        <asp:BoundField DataField="EndTime" HeaderText="End Time" 
            SortExpression="EndTime" />
        <asp:BoundField DataField="StaffUID" HeaderText="StaffUID" 
            SortExpression="StaffUID" Visible="false" />
    </Columns>
    <HeaderStyle BackColor="#264409" Font-Bold="True" ForeColor="White" />
    <AlternatingRowStyle BackColor="White" />
</asp:GridView>
4

2 に答える 2

0

データベースからレコードを削除するコード シーケンスは次のようになります。

//Declaring the datasource.
SqlDataSource SDSBooking= new SqlDataSource();

//Providing the delete command.
SDSBooking.DeleteCommand = "DELETE FROM Tbl_Booking WHERE BookingID_PK = @BookingID_PK";

//Adding the parameter for deleting the record.
SDSBooking.DeleteParameters.Add("BookingID_PK", GVMyBookings.Rows[e.RowIndex].Cells[1].Text);

//Providing the connection string.
SDSBooking.ConnectionString = connstring;

//Executing the delete method of the SqlDataSouce. 
//It is this line that will actually delete your record.
SDSBooking.Delete();

この後、このデータソースをグリッドビューに割り当てることができます。

注:の場合、データバインドされたフィールドがTableCellCollection のGVMyBookings.Rows[e.RowIndex].Cells[1].Textインデックスにあることを確認する必要があります。1

その前に他の列を生成している場合は、変更が必要になる場合があります。

あなたの場合、データバインドされたフィールドの前に削除ボタンが生成されるためです。したがって、削除ボタンはインデックス 0 になり、データバインド フィールド *BookingID_PK* はインデックス 1 になります。

于 2013-04-08T06:18:55.177 に答える