简体   繁体   中英

Cannot assign selected value from combobox to variable in SelectedIndexChanged event. Fill textboxes by combobox selection C# Winforms

In this form user update data about Client in client table. When form is loaded it fills textboxes whis data from client table by value in combobox. When user change value in combobox data int textboxes must change. But when I am trying to get Client ID from selected value in combobox event and assign it to getClientID variable compiler gives me error:

System.FormatException : Input string was not in a correct format.

 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;   
    }

During the load event ... there is no selected value ... it is null and cannot be converted to int. You have to wait until after databinding before you pull the selected value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM