如何通过更改组合框中所选项目来更改文本框中的文本?

时间:2014-03-19 10:25:03

标签: c# ssms-2012

我有combobox cmbCitytextbox txtReference。在表单加载时,组合框从我设法做的数据库中检索城市。我希望文本框改变参考号。存储在数据库中,在组合框中更改所选城市,我需要帮助。我正在使用visual studio 2012和SSMS 2012。

2 个答案:

答案 0 :(得分:0)

使用SelectedIndexChanged事件:

private void cmbCity_SelectedIndexChanged(object sender, EventArgs e)
{
        SqlConnection con = new SqlConnection(@"Data Source=YourSERVER;Initial Catalog=YourDataBaseName;User ID=DBUserName;Password=DBPassword");
        SqlCommand com = new SqlCommand("select top 1 * from yourTable where someCondition=true",con);
        SqlDataAdapter adp = new SqlDataAdapter(com);
        DataTable dt = new DataTable();
        adp.Fill(dt);
        txtReference.Text = dt.Rows[0]["refrence_no"].ToString();
}

在每个选择中查询数据库都不是明智之举 - 但是我沿着你提出问题的方式去了。

答案 1 :(得分:0)

在表单加载中,您可以将DataTable附加到combobox.datasource,然后设置ValueMemberDisplayMember。在combobox selectedindexchange事件之后,您将管理ValueMember。代码是这样的:

private void Form1_Load(object sender, EventArgs e)
    {
        SqlConnection sql = new SqlConnection("connString");
        SqlCommand cmd = new SqlCommand("SELECT * FROM myTable;",sql);
        SqlDataAdapter adp = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        adp.Fill(dt);
        cmbCity.DataSource = dt;
        cmbCity.DisplayMember = "cityname";
        cmbCity.ValueMember = "refrence_no";
        txtReferenceNo.Text = cmbCity.SelectedItem.ToString();
    }

    private void cmbCity_SelectedIndexChanged(object sender, EventArgs e)
    {
        txtReferenceNo.Text = cmbCity.SelectedItem.ToString();
    }
相关问题