DataBinding:'System.Data.DataRowView'不包含名称为'name'的属性

时间:2014-09-15 09:41:27

标签: asp.net

Asp.code

<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource2" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged1" DataTextField="socialname">
    <asp:ListItem text="select">Comment using</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:prakashConnectionString %>" SelectCommand="SELECT [socialname] FROM [socialnetwork]"></asp:SqlDataSource>
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>

C#代码

SqlConnection con = new SqlConnection("****");
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        Bindddl();
        BindTitle();
        Label3.Text = DropDownList1.Items[0].Text;
    }
}

protected void Bindddl()
{

    con.Open();
    SqlCommand cmd = new SqlCommand("select * from socialnetwork", con);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds);
    DropDownList1.DataTextField = "socialname";
    DropDownList1.DataValueField = "name";
    DropDownList1.DataBind();
    con.Close();
}

protected void BindTitle()
{
    if (DropDownList1 != null)
    {
        foreach (ListItem li in DropDownList1.Items)
        {
            li.Attributes["title"] = "social/" + li.Value; // it ll set the value of items in dropdownlist as tooltip

        }
    }
}

protected void DropDownList1_SelectedIndexChanged1(object sender, EventArgs e)
{
    BindTitle();
    Label3.Text = DropDownList1.SelectedItem.Text;
    Label3.Text = "Commented by";
}

2 个答案:

答案 0 :(得分:1)

您尚未分配DataSource

DropDownList1.DataSource = ds.Tables[0];
DropDownList1.DataTextField = "socialname";
DropDownList1.DataValueField = "name";
DropDownList1.DataBind();

但是你已经使用了两者,aspx上的DataSourceID和代码隐藏DataSet。对于SqlDataSource,您尚未选择名称,但仅限于:

SELECT [socialname] FROM [socialnetwork]

只需删除SqlDataSource,这只是多余的。

另外,我建议使用using - 语句进行连接,并建议使用dataadapter来确保处理所有非托管资源并关闭连接(即使出错):

DataSet ds = new DataSet();
using(SqlConnection con = new SqlConnection("****"))
using(SqlDataAdapter da = new SqlDataAdapter("select * from socialnetwork", con))
    da.Fill(ds);  // you don't need to open/close the connection with Fill
DropDownList1.DataSource = ds.Tables[0];
// ...

答案 1 :(得分:0)

我使用asp.net列表框遇到了类似的问题。我将我返回的列的名称更改为显示值字段以匹配错误条件中的名称并解决了问题。例如,我收到了这个错误:

[HttpException (0x80004005): DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'DisplayValue'.]

从SELECT语句返回的值保存在名为theValue的列中。我将列别名更改为DisplayValue:

SELECT theValue as DisplayValue
FROM whateverTable

注意我在VS 2012工作。