簡體   English   中英

用組合框選擇C#中的mysql數據值填充文本框

[英]Populating textbox with mysql data values from combobox selection c#

我試圖用數據庫中的值填充文本框,以便當用戶從組合框中選擇教師姓名時,文本框將填充其聯系方式。 這是我到目前為止的代碼。 沒有錯誤,但是當我從組合框中選擇一個值時,文本框仍然為空白。

    private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        MySqlConnection cs = new MySqlConnection(connectionSQL);
        cs.Open();

        DataSet ds = new DataSet();

        MySqlDataAdapter da = new MySqlDataAdapter("Select * from Teacher WHERE name='" + comboBox1.Text + "'", cs);

        MySqlCommandBuilder cmd = new MySqlCommandBuilder(da);

        da.Fill(ds);


        if (comboBox1.SelectedIndex > 0)
        {


            NameBox.Text = ds.Tables[0].Rows[0]["name"].ToString();
            AddressBox.Text = ds.Tables[0].Rows[0]["address"].ToString();

        }

任何幫助或建議,將不勝感激

我必須相信,根據您的代碼,問題就在這里:

if (comboBox1.SelectedIndex > 0)

如果列表中只有一個項目, 或者用戶選擇了第一個項目,則查詢將運行,但不會填充文本框。

AddressBox.DataBind();
NameBox.DataBind();

在驗證所選索引之前,您正在查詢數據庫,並且應該檢查所選索引是否大於-1,而不是0。

private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (comboBox1.SelectIndex < 0) 
    {
        // Don't want to suffer database hit if nothing is selected
        // Simply clear text boxes and return
        NameBox.Text = "";
        AddressBox.Text = "";
    }
    else 
    {
        MySqlConnection cs = new MySqlConnection(connectionSQL);
        cs.Open();

        DataSet ds = new DataSet();

        // You only need to select the address since you already have the name unless 
        // they are displayed differently and you want the database display to show
        MySqlDataAdapter da = new MySqlDataAdapter("Select address from Teacher WHERE name='" + comboBox1.Text + "'", cs);

        MySqlCommandBuilder cmd = new MySqlCommandBuilder(da);

        da.Fill(ds);

        NameBox.Text = comboBox1.Text;
        AddressBox.Text = ds.Tables[0].Rows[0]["address"].ToString();
    }
}

另外,如果名稱在組合框中的顯示方式與數據庫中顯示的方式不同,則很容易錯過,例如名字和姓氏之間有多余的空格,或者其他很難看到的東西,可能導致查詢不匹配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM