无法绑定到新的显示成员C#

时间:2012-07-19 01:57:51

标签: c# winforms combobox member

我收到此错误:无法绑定到新的显示成员C#

        sConn = new SqlConnection(sStr);
        daSched = new SqlDataAdapter("Select Subject from Schedules where Username = '" + lblUsername.Text + "'", sConn);
        dsSched = new DataSet();
        daSched.Fill(dsSched, "Schedules");
        dsSched.Tables["Schedules"].PrimaryKey = new DataColumn[] { dsSched.Tables["Schedules"].Columns["ScheduleID"] };

        cbxSubject.DataSource = dsSched.Tables["Schedules"];
        cbxSubject.DisplayMember = "Schedule";
        cbxSubject.ValueMember = "ScheduleID";
        cbxSubject.Text = "Choose Subject";

我不知道哪里出了问题。这是表格预览表的预览:http://i47.tinypic.com/1zzoz5z.png

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

您的表中没有名为“Schedule”的字段,因此控件无法找到名为Schedule的成员,并且您只选择了Subject

ScheduleID已经是您的主键,因此您最好将Sql Query更改为:

Select ScheduleID, Subject From ...(你也可能应该parameterize

这一行 - > dsSched.Tables["Schedules"].PrimaryKey = new DataColumn[] { dsSched.Tables["Schedules"].Columns["ScheduleID"] };是不必要的。

据我所知,我相信你希望你的显示成员成为“主题”

此外 - 您应该打开您的连接(我在您的帖子中没有看到它) - 并且更理想地将其包装在using语句中

类似的东西:

using (SqlConnection con = new SqlConnection(connectionString))
    {
        string userName = lblUsername.Text;
        con.Open(); 
        var adapter = new SqlDataAdapter("Select ScheduleID, Subject From 
                                 Schedules Where Username = @username", conn);
        adapter.Parameters.Add("@username", SqlDbType.VarChar, 50, userName)
        var dsSched = new DataSet();
        adapter.Fill(dsSched);

        cbxSubject.DataSource = dsSched.Tables[0];
        cbxSubject.DisplayMember = "Subject";
        cbxSubject.ValueMember = "ScheduleID";
        cbxSubject.DataBind();

    }