c# – Combobox数据绑定显示system.data.datarowview

我将combobox与datasource,displaymember,valuemember绑定.它在我的电脑上工作正常,但它不适用于客户端电脑.以下是我的源代码:

从UserControl的构造函数调用cbxAlloyBinding方法.

private void cbxAlloyBinding()
    {
        DataTable dt = new DataTable();
        SqlDataAdapter adp = new SqlDataAdapter("SELECT alloyName,alloyId FROM alloy", con);
        adp.Fill(dt);

        if (dt.Rows.Count > 0)
        {
            cbxMetal.DisplayMember = "alloyName";
            cbxMetal.ValueMember = "alloyId";
            cbxMetal.DataSource = dt;
        }
        else
        {
            cbxMetal.Text = "";
        }
    }

    private void cbxMetal_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (cbxMetal.SelectedIndex != -1)
        {
            DataTable dt = new DataTable();
            tempcmd = new SqlCommand("SELECT specification,alloyCode FROM alloy where alloyId='" + cbxMetal.SelectedValue + "'", con);
            SqlDataAdapter adp = new SqlDataAdapter(tempcmd);
            adp.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                txtSpecification.Text = dt.Rows[0]["alloyCode"].ToString();
                txtSupplyConditions.Text = dt.Rows[0]["specification"].ToString();
                cbxheatBinding();
            }
            else
            {
                txtSpecification.Text = "";
            }

        }
    }

这让我困扰了最近两天,我几乎尝试了所有的技巧,但它仍然无法正常工作.

客户端的PC使用的是Windows 7 ultimate,sql server 2005和.net framework 3.5.

解决方法:

如果在构造函数中调用cbxAlloyBinding()之前调用了cbxMetal_SelectedIndexChanged,则肯定会发生这种情况.

例如(请参阅下面的代码),您可能在构造函数中有其他组合框绑定,这可能在构造函数中的cbxAlloyBinding()之前,并且这些绑定正在调用cbxMetal_SelectedIndexChanged.

public Constructor()
{
        InitializeComponent();

        cbxheatBinding();      //1st Three Binding Methods may be somehow related to your cbxMetal,
        dtpStartDateBinding(); //which leads them to call cbxMetal_SelectedIndexChanged method.
        dtpEndDateBinding();
        cbxAlloyBinding();
}

我怀疑你的cbxMetal.DataSource是从你的代码中的其他一点设置的,并且在分配了DisplayMember和ValueMember之前;

请记住,System.DataRow.DataRowView只会发生

ComboBox.SelectedValue is called before ValueMember assignment.

上一篇:c #databound ComboBox:InvalidArgument =值’1’对’SelectedIndex’无效


下一篇:c# – 如何检查组合框下拉列表是否向上或向下显示?