gridview删除并选择不工作(使用datakeynames)

时间:2015-08-12 17:36:27

标签: c# asp.net gridview

所以我有一个gridview填充了来自objectdatasource的数据。在该objectdatasource中,我还添加了删除和选择方法。但是,由于某种原因,删除和选择不起作用(或者我得到错误必须在GridView'GridView1'上指定数据键才能检索所选数据键。使用DataKeyNames属性指定数据键。 ,或者它什么都不做)。这意味着datakeyname没有设置或错误,但设置了(据我所知,它是正确的)?

我正在使用BO和DAL课程。

BO:

    public int OrderID
    {
        get { return _ID; }
        set { _ID = value; }
    }

DAL(删除),如果我得到删除,我会尝试再次找出自己。

[DataObjectMethodAttribute(DataObjectMethodType.Delete, true)]
    public static int DeleteOrder(Int32 OrderID)
    {
        SqlConnection conn = new SqlConnection(GetConnectionString());

        string sql =
          "DELETE FROM tblOrders WHERE ID=@OrderID";

        SqlCommand cmd = new SqlCommand(sql, conn);
        cmd.Parameters.AddWithValue("@OrderID", OrderID);

        conn.Open();
        int i = cmd.ExecuteNonQuery();
        conn.Close();

        return i;
    }

aspx(gridview):

<asp:GridView ID="GridView1" runat="server" DataKeyNames="OrderID" DataSourceID="dtsrcOrder" AutoGenerateColumns="False" AllowPaging="True"
      EnableViewState="False" CssClass="gv" GridLines="None" Height="63px" Width="527px" CellPadding="4" ForeColor="#333333">
          <Columns>
              <asp:BoundField DataField="OrderID" HeaderText="ID" SortExpression="OrderID"></asp:BoundField>
              <asp:BoundField DataField="OrderNAME" HeaderText="Naam" SortExpression="OrderNAME"></asp:BoundField>
              <asp:BoundField DataField="OrderBOOK_ID" HeaderText="Boek" SortExpression="OrderBOOK_ID"></asp:BoundField>
              <asp:BoundField DataField="OrderCOUNT" HeaderText="Aantal" SortExpression="OrderCOUNT"></asp:BoundField>
              <asp:CheckBoxField DataField="OrderPAID" HeaderText="Betaald" SortExpression="OrderPAID"></asp:CheckBoxField>

              <asp:CommandField ShowDeleteButton="True" ShowSelectButton="True"></asp:CommandField>
          </Columns>
      </asp:GridView>

aspx objectdatasource:

        <asp:ObjectDataSource ID="dtsrcOrder" runat="server" DeleteMethod="DeleteOrder" SelectMethod="GetOrdersbyID" TypeName="DAL.OrdersDAL"
        DataObjectTypeName="BO.Order">
        <DeleteParameters>
            <asp:Parameter Name="OrderID" Type="Int32"></asp:Parameter>
        </DeleteParameters>
        <SelectParameters>
            <asp:ControlParameter ControlID="GridView1" PropertyName="SelectedValue" Name="OrderID" Type="Int32"></asp:ControlParameter>
        </SelectParameters>
    </asp:ObjectDataSource>

有人可以发现我的错误吗?

1 个答案:

答案 0 :(得分:0)

您的语句包含语法错误:

string sql = "DELETE FROM tblOrders WHERE ID=@OrderID";

尝试:

sql = "DELETE tblOrders WHERE ID=@OrderID";

此外,您可以尝试使用SQL DataSource代替Object DataSource来简化您的解决方案。希望这可能有所帮助。