【发布时间】:2021-06-19 20:51:09
【问题描述】:
我正在使用已填充 MySQL 数据表中的数据的 Winform ComboBoxes。它们是级联的组合框,所以无论我从第一个组合框(即国家/地区)中选择什么,都将确定第二个组合框中名为City 的项目
Main Screen
我的问题是,当我更新我的客户 DataGridView 时,之前选择的项目没有显示在我的更新表单的 ComboBox 中;第一项默认显示。奇怪的是,这只是第二个 ComboBox 的问题,City
Update Form Showing the Incorrect City Value
第一个 Country 显示之前选择的项目。
Update Form Showing the Correct Country Value
当我关闭更新表单,然后尝试在主屏幕上第二次更新同一客户时,City ComboBox 显示正确的值。
Update Form now shows the Correct value for both City and Country
我需要帮助来弄清楚我可以做些什么来使第二个组合框的先前选择的值正常工作。我还想提前感谢任何人提供的任何帮助或澄清,我可以用来解决这个问题。
这是我的一些代码:
private void CBxCountry_SelectedIndexChanged(object sender, EventArgs e)
{
if(CBxCountry.SelectedValue.ToString() != null)
{
countryId = Convert.ToInt32(CBxCountry.SelectedValue);
refreshcity(countryId);
}
}
private void refreshcity(int countryId)
{
con.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * FROM city WHERE countryId = @countryId", con);
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
cmd.Parameters.AddWithValue("countryId", countryId);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Close();
CbxCity.DisplayMember = "city";
CbxCity.ValueMember = "cityId";
CbxCity.DataSource = dt;
CbxCity.Enabled = true;
City = this.CbxCity.GetItemText(this.CbxCity.SelectedItem);
}
public void UpdateCustomer()
{
LblAddUpdateCustomer.Text = "Update Customer";
BtnUpdateSave.Text = "Update";
TxtNameAdd.Text = CustomerName;
TxtAddressAdd.Text = Address;
CbxCity.Text = City;
CBxCountry.Text = Country;
TxtZipAdd.Text = PostalCode;
TxtPhoneAdd.Text = Phone;
}
这是我第一次在这里寻求帮助,所以我希望我提供了足够的信息。
【问题讨论】:
-
使用具有 3 个表(客户、城市、国家/地区)和 3 个数据关系(客户->城市、客户->国家/城市->国家/地区的强类型数据集,箭头指向主键端)和一个带有 citybindingsource 的表单,该表单绑定到 country bindingsource 暴露的 city_country 数据关系