2012-08-31 78 views
1

如何將GridView中的行的id鏈接到deletecommand以便刪除一行?如何在GridView中刪除

這裏是我的代碼:

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
     AllowSorting="True" DataSourceID="SqlDataSource1" 
     AutoGenerateColumns="False"> 
    <Columns> 
     <asp:CommandField ShowDeleteButton="True" /> 
     <asp:BoundField DataField="SDate" HeaderText="SDate" SortExpression="SDate" /> 
     <asp:BoundField DataField="STime" HeaderText="STime" SortExpression="STime" /> 
     <asp:BoundField DataField="SPrice" HeaderText="SPrice" 
       SortExpression="SPrice" /> 
     <asp:BoundField DataField="SDuration" HeaderText="SDuration" 
       SortExpression="SDuration" /> 
     <asp:BoundField DataField="SNoPlaces" HeaderText="SNoPlaces" 
       SortExpression="SNoPlaces" /> 
     <asp:BoundField DataField="ScheduleId" HeaderText="ScheduleId" 
       InsertVisible="False" ReadOnly="True" SortExpression="ScheduleId" /> 
    </Columns> 
</asp:GridView> 
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
     ConnectionString="<%$ ConnectionStrings:ChinatowndbConnString %>" 
     DeleteCommand="DELETE FROM Schedule WHERE (ScheduleId = @ScheduleId)" 
     SelectCommand="SELECT SDate, STime, SPrice, SDuration, SNoPlaces, ScheduleId FROM Schedule"> 
    <DeleteParameters> 
     <asp:Parameter Name="ScheduleId" /> 
    </DeleteParameters> 
</asp:SqlDataSource> 

我使用Visual Studio 2010中

回答

3

你忘了設置DataKeyNames property在GridView控件。

更改你的GridView這樣的:

<asp:GridView ID="GridView1" runat="server" AllowPaging="True"  
    AllowSorting="True" DataSourceID="SqlDataSource1"  
    AutoGenerateColumns="False" 
    DataKeyNames="ScheduleId" > 

另一個例子:SqlDataSource.DeleteCommand Property

0

鏈接你的id在GridView屬性

DataKeyNames="your_id" 

您還可以定義如下多個ids

DataKeyNames="your_id1, your_id2" 

您可以訪問如下值:

protected void GridView1_Deleting(object sender, ObjectDataSourceMethodEventArgs) 
{ 
    //e.Command.Parameters["your_id1"].Value; 
}