Databind()Visual Studio 2015的问题

时间:2017-03-23 18:38:39

标签: c# visual-studio-2015

尝试将数据绑定到列表框。我在我的项目中多次使用DataBind没有问题,在这里我不明白问题是什么。 当我使用DataBind()时,我收到了这个错误。

An exception of type 'System.Web.HttpException' occurred in System.Web.dll but was not handled in user code

Additional information: DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'Motherboards'.

ASP:

<asp:ListBox ID="lbCategories" runat="server"></asp:ListBox>

C#:

protected void getCategories()
{
    DAL dal = new DAL(conn);
    dal.AddParam("all", "0");
    DataSet ds = dal.ExecuteProcedure("spGetCats");

    lbCategories.DataSource = ds.Tables[0];
    lbCategories.DataTextField = ds.Tables[0].Rows[0]["catName"].ToString();
    lbCategories.DataValueField = ds.Tables[0].Rows[0]["catID"].ToString();
    lbCategories.DataBind();
}

数据库表:

CREATE TABLE tbCats (
    catID INT IDENTITY(1,1) PRIMARY KEY,
    catName VARCHAR(32)
)

程序:

CREATE PROCEDURE spGetCats(
    @all CHAR NULL
)
AS BEGIN
    IF @all IS NULL
        SELECT * FROM tbCats
    ELSE
        SELECT * FROM tbCats WHERE catID <> 1
END
GO

插入内容:

INSERT INTO tbCats (catName) VALUES ('All'), ('Motherboards'), ('Memory'), ('Hard Drive'), ('SSDs'), ('CPUs'),
                                    ('Video Cards'), ('Computer Cases'), ('Monitors'), ('Keyboards'), ('Mice')

2 个答案:

答案 0 :(得分:0)

DataTextFieldDataValueField必须是列名。您的代码是将它们设置为第一行中的值。

protected void getCategories()
{
    DAL dal = new DAL(conn);
    dal.AddParam("all", "0");
    DataSet ds = dal.ExecuteProcedure("spGetCats");

    lbCategories.DataSource = ds.Tables[0];
    lbCategories.DataTextField = "catName";
    lbCategories.DataValueField = "catID";
    lbCategories.DataBind();
}

答案 1 :(得分:0)

您需要更改以下行:

1a23x

为:

lbCategories.DataTextField = ds.Tables[0].Rows[0]["catName"].ToString();
lbCategories.DataValueField = ds.Tables[0].Rows[0]["catID"].ToString();

或者这可能也有效:

lbCategories.DataTextField = "catName";
lbCategories.DataValueField = "catID";

它需要在源中查找的列的名称,该列将被绑定为显示文本和值,您当前的代码是要查找第一行中的值主板和您的数据源中没有列名称。