[英]Delete a row from gridview in back end c#
我想刪除后端的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();
}
gridview是:
<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>
似乎您的查詢不正確
DELETE * FROM Tbl_Booking WHERE ID=@BookingID_PK
請改用它
DELETE FROM Tbl_Booking WHERE ID=@BookingID_PK
從此行中刪除@
symbole
SDSBooking.DeleteParameters.Add("BookingID_PK",...);
然后針對dataSource顯式調用Delete
...
SDSStudents.ConnectionString = connstring;
SDSStudents.Delete();
GridView1.DataSource = SDSStudents;
...
從數據庫中刪除記錄的代碼序列應該是這樣的。
//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();
在此之后,您可以將此數據源分配給gridview。
注意:對於GVMyBookings.Rows[e.RowIndex].Cells[1].Text
,您需要確保您的數據綁定字段位於TableCellCollection中的索引1
。
如果要在其之前生成其他列,則可能需要更改。
因為在您的情況下,將在數據綁定字段之前生成刪除按鈕。 因此刪除按鈕將位於索引0處,您的數據綁定字段* BookingID_PK *將位於索引1處。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.