ComboBox绑定到SQL DB

时间:2013-11-05 12:41:36

标签: c# visual-studio-2012 data-binding combobox databound

我有一个SQL数据库,其中两个表具有PK Relation。 tblProject.contractorID是外键列,tblCompany.contractorID是主键列。

sql

我创建了一个Windows窗体,将tblProject.contractorID标记为ComboBox,将tblProject标记为Details,然后将tblProject拖放到窗体中。现在,我有tblProject的标签,文本框和组合框以及相关的绑定导航器。 (ihaleDataSet,tblProjectBindingSource,tblProjectTableAdapter,tableAdapterManager和tblProjectBindingNavigator)

2 当我运行项目并单击contractorID ComboBox时,我想显示tblCompany.shortName值。选择其中一个值后,我想将tblCompany.contractorID值写入tblProject.ContractorID并进行相应的记录。

我尝试了数据绑定模式(DataSource = tblCompanyBindingSource,DisplayMember =“shortName”,ValueMember =“companyID”)

enter image description here

        // 
        // contractorIDComboBox
        // 
        this.contractorIDComboBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.tblProjectBindingSource, "contractorID", true));
        this.contractorIDComboBox.DataSource = this.tblCompanyBindingSource;
        this.contractorIDComboBox.DisplayMember = "shortName";
        this.contractorIDComboBox.FormattingEnabled = true;
        this.contractorIDComboBox.Location = new System.Drawing.Point(181, 100);
        this.contractorIDComboBox.Name = "contractorIDComboBox";
        this.contractorIDComboBox.Size = new System.Drawing.Size(121, 21);
        this.contractorIDComboBox.TabIndex = 8;
        this.contractorIDComboBox.ValueMember = "companyID";

它不起作用。我该怎样做才能实现我的目标?

1 个答案:

答案 0 :(得分:1)

我已经解决了这个问题。只需在第一行中将“Text”替换为“SelectedValue”即可。

更多信息是here