无法将选定的值从组合框分配给SelectedIndexChanged事件中的变量。通过组合框选择C#Winforms填充文本框

时间:2015-04-13 14:07:47

标签: c# winforms entity-framework combobox

在此表单中,用户更新有关客户端表中客户端的数据。加载表单时,它会在组合框中按值填充客户端表格中的文本框数据。当用户更改组合框数据中的值时,文本框必须更改。 但是当我试图从组合框事件中的选定值获取客户端ID并将其分配给getClientID变量时,编译器会给出错误:

  

System.FormatException:输入字符串的格式不正确。

 private void ClientUpdateForm_Load(object sender, EventArgs e)
    {
        ClientComboBox.DataSource = AgencyContext.Client.ToList();
        ClientComboBox.DisplayMember = "ClientName";
        ClientComboBox.ValueMember = "ClientID";
        Invalidate();
        int getClientID = Convert.ToInt32(ClientComboBox.SelectedValue.ToString());
        var fillTextBoxes = (from t in AgencyContext.Client where t.ClientID == getClientID select t).Single();
        ClientNametextBox.Text = fillTextBoxes.ClientName;
        ClientBirthtextBox.Text = fillTextBoxes.Birth.ToString(CultureInfo.CurrentCulture);
        ClientPhonetextBox.Text = fillTextBoxes.Phone.ToString();
        ClientPassporttextBox.Text = fillTextBoxes.Passport;
        AddresstextBox.Text = fillTextBoxes.Address;
        ClientStatetextBox.Text = fillTextBoxes.State;
        ClientCitytextBox.Text = fillTextBoxes.City;      
    }

    private void SaveNewClientButton_Click(object sender, EventArgs e)
    {

    }

    private void ClientComboBox_SelectedIndexChanged(object sender, EventArgs e)
    {
            var getClientID = Convert.ToInt32(ClientComboBox.SelectedValue.ToString());
            var fillTextBoxes = (from t in AgencyContext.Client where t.ClientID == getClientID select t).Single();
            ClientNametextBox.Text = fillTextBoxes.ClientName;
            ClientBirthtextBox.Text = fillTextBoxes.Birth.ToString(CultureInfo.CurrentCulture);
            ClientPhonetextBox.Text = fillTextBoxes.Phone.ToString();
            ClientPassporttextBox.Text = fillTextBoxes.Passport;
            AddresstextBox.Text = fillTextBoxes.Address;
            ClientStatetextBox.Text = fillTextBoxes.State;
            ClientCitytextBox.Text = fillTextBoxes.City;   
    }

1 个答案:

答案 0 :(得分:0)

在加载事件期间...没有选定的值...它为null并且无法转换为int。您必须等到数据绑定后再拉出所选值。