ObjectDataSource 未正确绑定到 GridView

ObjectDataSource Not Binding Properly To GridView

这可能很简单,只是需要一些新鲜的眼光。它很长,但我想给出完整的上下文。我试图显示一个使用 ObjectDataSource 的 GridView。 ODS returns 一个数据Table。 DT 由 MSSQL 存储过程的查询结果构造而成。问题是我的 ASP BoundField 抱怨我想要一个不在数据源中的字段......但它确实是。当我省略上述字段时,网格显示正常,但当我按 "Delete" 时,一个 0 的 id 被发送到我的 ODS,而不是实际删除记录的 70。我没有尝试更新但是,但我想如果其他两个不这样做,那是行不通的。我做错了什么?

网格视图:

<asp:GridView 
    AllowPaging="True" 
    AllowSorting="True" 
    AutoGenerateColumns="False" 
    CellPadding="4" 
    CssClass="table" 
    DataSourceID="ExcludeODS" 
    EnableViewState="True" 
    ForeColor="#333333" 
    GridLines="None" 
    ID="ExcludeGridView" 
    runat="server">
    <AlternatingRowStyle BackColor="White"></AlternatingRowStyle>
    <Columns>
        <asp:BoundField DataField="RuleKey" HeaderText="Rule Key"></asp:BoundField>
        <asp:BoundField DataField="Field" HeaderText="Field"></asp:BoundField>
        <asp:TemplateField ShowHeader="False">
            <ItemTemplate>
                <asp:LinkButton 
                    runat="server" 
                    CommandName="Edit"><span class="fa fa-pencil"> Edit</span>
                </asp:LinkButton>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField ShowHeader="False">
            <ItemTemplate>
                <asp:LinkButton 
                    runat="server" 
                    CommandName="Delete" 
                    OnClientClick="if(!confirm('Are you sure you want to delete this?')){ return false; };"><span class="fa fa-trash"> Delete</span>
                </asp:LinkButton>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
    <EditRowStyle BackColor="#2461BF"></EditRowStyle>
    <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White"></FooterStyle>
    <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White"></HeaderStyle>
    <PagerStyle HorizontalAlign="Center" BackColor="#2461BF" ForeColor="White"></PagerStyle>
    <RowStyle BackColor="#EFF3FB"></RowStyle>
    <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333"></SelectedRowStyle>
    <SortedAscendingCellStyle BackColor="#F5F7FB"></SortedAscendingCellStyle>
    <SortedAscendingHeaderStyle BackColor="#6D95E1"></SortedAscendingHeaderStyle>
    <SortedDescendingCellStyle BackColor="#E9EBEF"></SortedDescendingCellStyle>
    <SortedDescendingHeaderStyle BackColor="#4870BE"></SortedDescendingHeaderStyle>
</asp:GridView>

ObjectDataSource (.ASPX):

<asp:ObjectDataSource 
    runat="server" 
    ID="ExcludeODS" 
    DeleteMethod="CtDeleteExcludeRules" 
    InsertMethod="CtAddExcludeRules" 
    SelectMethod="CtGetExcludeRules" 
    TypeName="CustomerTypeRules.DAL.CtExcludeRules" 
    UpdateMethod="CtUpdateExcludeRules">
    <DeleteParameters>
        <asp:Parameter Name="id" Type="Int32" ></asp:Parameter>
        <asp:Parameter Name="userId" Type="String"></asp:Parameter>
    </DeleteParameters>
    <InsertParameters>
        <asp:Parameter Name="ruleKey" Type="String"></asp:Parameter>
        <asp:Parameter Name="field" Type="String"></asp:Parameter>
        <asp:Parameter Name="userId" Type="String"></asp:Parameter>
    </InsertParameters>
    <SelectParameters>
        <asp:ControlParameter 
            ControlID="RuleDropDown" 
            PropertyName="SelectedValue" 
            DefaultValue="null" 
            Name="ruleKey" 
            Type="String">
        </asp:ControlParameter>
    </SelectParameters>
    <UpdateParameters>
        <asp:Parameter Name="id" Type="Int32"></asp:Parameter>
        <asp:Parameter Name="field" Type="String"></asp:Parameter>
        <asp:Parameter Name="userId" Type="String"></asp:Parameter>
    </UpdateParameters>
</asp:ObjectDataSource>

ObjectDataSource (.CS):

public DataTable CtGetExcludeRules(
    string ruleKey // Length: 255
)
{
    SqlConnection dbConn = new SqlConnection(_connectString);
    SqlCommand command =
        new SqlCommand
        {
            CommandText = "CT_Get_ExcludeRules",
            CommandType = CommandType.StoredProcedure,
            Connection = dbConn
        };

    command.Parameters.Add(
        "@RuleKey", SqlDbType.VarChar, 255
    ).Value = ruleKey ?? "";

    dbConn.Open();

    DataTable dt = new DataTable();
    SqlDataAdapter da = new SqlDataAdapter(command);
    da.Fill(dt);

    dbConn.Close();
    da.Dispose();

    return dt.Rows.Count > 0 ? dt : new DataTable{Columns = { "ruleKey", "field" }, Rows = { "No results" }};
}

public bool CtDeleteExcludeRules(
    int id,
    string userId // Length: 50
)
{
    using (var dbConn = new SqlConnection(_connectString))
    {
        using (var command = new SqlCommand(
            "CT_Delete_ExcludeRules", dbConn
        ))
        {
            command.CommandType = CommandType.StoredProcedure;

            command.Parameters.Add(
                "@Id", SqlDbType.Int
            ).Value = id;

            command.Parameters.Add(
                "@UserId", SqlDbType.VarChar, 50
            ).Value = userId ?? "";

            dbConn.Open();

            return command.ExecuteNonQuery() > 0;
        }
    }
}

public bool CtUpdateExcludeRules(
    int id,
    string field, // Length: 50
    string userId // Length: 50
)
{
    using (var dbConn = new SqlConnection(_connectString))
    {
        using (var command = new SqlCommand(
            "CT_Update_ExcludeRules", dbConn
        ))
        {
            command.CommandType = CommandType.StoredProcedure;

            command.Parameters.Add(
                "@Id", SqlDbType.Int
            ).Value = id;

            command.Parameters.Add(
                "@Field", SqlDbType.VarChar, 50
            ).Value = field;

            command.Parameters.Add(
                "@UserId", SqlDbType.VarChar, 50
            ).Value = System.Web.HttpContext.Current.User.Identity.Name
                      ?? "";

            dbConn.Open();

            return command.ExecuteNonQuery() > 0;
        }
    }
}

存储过程:

[dbo].[CT_Get_ExcludeRules]
@RuleKey varchar(255) = ''
AS
SELECT * FROM [Interface].[dbo].[CT_ExcludeRules] WHERE RuleKey = @RuleKey;


[dbo].[CT_Delete_ExcludeRules]
@Id int,
@UserId varchar(50)
as

BEGIN TRANSACTION;  
BEGIN TRY  

    insert into CT_ExcludeRules_History
    select Id,RuleKey,Field,@UserId,'Delete',getdate()
    from CT_ExcludeRules
    where Id = @Id

    delete from [dbo].[CT_ExcludeRules]
    where Id = @Id

    Commit
END TRY 


[CT_Update_ExcludeRules]
@Id int,
@Field varchar(50),
@UserId varchar(50)
as

BEGIN TRANSACTION;  
BEGIN TRY  
    Update [dbo].[CT_ExcludeRules]
    set Field = @Field
    where Id = @Id

    insert into CT_ExcludeRules_History
    select Id,RuleKey,Field,@UserId,'Update',getdate()
    from CT_ExcludeRules
    where Id = @Id

    Commit
END TRY  

Table设计:

GET 存储过程示例:

DataTable 行结果视图(也是数据源的 OnSelected 事件检索到的相同数组):

单击后传递给数据源的值"Delete":

尝试向 GridView 添加 Id 列时出现以下错误消息:

A field or property with the name 'Id' was not found on the selected data source.

我不需要 id 列,我只想像普通的 GridView 一样删除和更新!

解决方案:

感谢下面的用户 "sea-charp" 查看缺少的内容。我需要将 { "ruleKey", "field" } 替换为 { "id", "ruleKey", "field" } 以便我的数据源识别 "Id" 属性。一旦识别出来,我就可以在我的 GridView 的 DataKeyNames 属性中添加 "Id",这通过 70 而不是 0 的正确 ID 完全启用了我的删除方法。

而不是这个:

command.Parameters.Add(
        "@RuleKey", SqlDbType.VarChar, 255
    ).Value = ruleKey ?? "";

试试这个

command.Parameters.Add("@RuleKey", SqlDbType.VarChar, 255);
command.Parameters("@RuleKey").Value = ruleKey ?? "";

您似乎遇到了错误,因为您将此作为 return 语法的一部分:

DataTable{Columns = { "ruleKey", "field" }, Rows = { "No results" }};

... 其中 return 是一个 table,没有结果时没有 ID - 可能是因为您使用的命令参数语法。