我正在创建一个简单的发票应用程序,它从表单中获取一些细节并创建PDF文件。数据存储在SQL Server数据库中。
问题在于客户选择组合框控件,其中显示的项目在选择时未显示正确的客户信息。第一项显示数据库中最后一条记录的详细信息,反之亦然。
有问题的控件:
Customer
表:
表单加载时的数据绑定,IMSDBAccess
是一个处理数据库查询的类:
private void InvoiceDetails_Load(object sender, EventArgs e)
{
txtBillingAddress.DataBindings.Add("Text", IMSDBAccess.queryDB("SELECT streetaddress FROM Customer"), "streetaddress");
txtPostcode.DataBindings.Add("Text", IMSDBAccess.queryDB("SELECT postzip FROM Customer"), "postzip");
txtCity.DataBindings.Add("Text", IMSDBAccess.queryDB("SELECT towncity FROM Customer"), "towncity");
txtState.DataBindings.Add("Text", IMSDBAccess.queryDB("SELECT stateprovince FROM Customer"), "stateprovince");
txtCountry.DataBindings.Add("Text", IMSDBAccess.queryDB("SELECT country FROM Customer"), "country");
cboCustomer.DataSource = IMSDBAccess.queryDB("SELECT customerNo, (RTRIM(business_name) + ' (' + CONVERT(varchar(10), customerNo) + ')') AS DisplayValue FROM Customer");
cboCustomer.BindingContext = this.BindingContext;
cboCustomer.DisplayMember = "DisplayValue";
cboCustomer.ValueMember = "customerNo";
}
当组合框中所选项目发生变化时:
private void cboCustomer_SelectedIndexChanged(object sender, EventArgs e)
{
updateCustomer();
}
Combobox更新方法:
private void updateCustomer()
{
MessageBox.Show(cboCustomer.SelectedValue.ToString());
int cNo;
bool parseOK = Int32.TryParse(cboCustomer.SelectedValue.ToString(), out cNo);
string query = "SELECT * FROM Customer WHERE customerNo = @customerNo";
SqlConnection connectionObj = new SqlConnection(IMSDBAccess.GetConnectionString(""));
SqlCommand cmd = new SqlCommand(query, connectionObj);
SqlDataReader reader;
cmd.Parameters.AddWithValue("@customerNo", cNo);
try
{
connectionObj.Open();
reader = cmd.ExecuteReader();
if (reader.Read())
{
txtBillingAddress.Text = reader["streetaddress"].ToString();
txtCity.Text = reader["towncity"].ToString();
txtState.Text = reader["stateprovince"].ToString();
txtCountry.Text = reader["country"].ToString();
txtPostcode.Text = reader["postzip"].ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error updating customer info", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
}
}
我无法理解如何以正确的顺序绑定数据,以便cboCustomer中的项目对应于文本框中显示的数据。
答案 0 :(得分:0)
在执行updateCustomer命令时,您似乎试图通过显式设置文本框的值来覆盖绑定。相反,当组合的值发生更改时,请查看使用INotifyPropertyChanged更新值。对于类似的例子来说并不是这样,但这可能会有所帮助:Data binding for TextBox