值ComboBox在C#中更改TextBox的值

时间:2015-05-13 07:57:23

标签: c# winforms combobox

您好专家我使用此代码前段时间工作,但现在不工作...... !!它说

  

(转换varchar值时转换失败   ' System.Data.DataRowView'到数据类型int)

代码是组合框选择值更改文本框,带有此值的详细信息并提前感谢。

 public partial class test : Form
{

    SqlConnection cn = new SqlConnection("Server=AMEER;DataBase=custemer_net;Integrated security=true");
    SqlDataAdapter da;
    DataTable dt = new DataTable();
    DataTable dttt = new DataTable();
    public test()
    {
        InitializeComponent();
        da = new SqlDataAdapter("Select *from subscrbtion ", cn);
        da.Fill(dt);
        comboBox1.DisplayMember = "name";
        comboBox1.ValueMember = "id";
        comboBox1.DataSource = dt;

    }

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        da = new SqlDataAdapter("select * from subscrbtion where id='" + comboBox1.SelectedValue + "'", cn);
        da.Fill(dttt);
        textBox1.Text = dttt.Rows[0]["phone"].ToString();
    }

1 个答案:

答案 0 :(得分:0)

我认为你的SqlDataAdapter有错:

new SqlDataAdapter("select * from subscrbtion where id='" + comboBox1.Text + "'", cn);

应该是

new SqlDataAdapter("select * from subscrbtion where id='" + comboBox1.SelectedValue + "'", cn);

SelectedValue将指向您在ValueMember下声明的ID。

额外:在声明其数据/值成员后设置您的组合框数据源:

comboBox1.DisplayMember = "name";
comboBox1.ValueMember = "id";
comboBox1.DataSource = dt;

根据以下内容更改您的代码:

public test()
{
    InitializeComponent();

    using(SqlConnection cn = new SqlConnection("Server=AMEER;DataBase=custemer_net;Integrated security=true"))
    {
        var adapter = new SqlDataAdapter("Select *from subscrbtion ", cn);
        adapter.Fill(dt);
    }
    comboBox1.DisplayMember = "name";
    comboBox1.ValueMember = "id";
    comboBox1.DataSource = dt;
}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    //for testing
    MessageBox.Show(comboBox1.SelectedValue.ToString());
    //

    //clear the datatable dttt
    dttt.Clear();                  //<----------THIS SHOULD BE YOUR NEW SOLUTION

    //refill the datatable with the new information
    using(SqlConnection cn = new SqlConnection("Server=AMEER;DataBase=custemer_net;Integrated security=true"))
    {
        var adapter = new SqlDataAdapter("select * from subscrbtion where id='" + comboBox1.SelectedValue + "'", cn);
        adapter.Fill(dttt);
    }
    //for testing
    MessageBox.Show(dttt.Rows.Count.ToString());
    //

    //show the data inside the textbox.
    textBox1.Text = dttt.Rows[0]["phone"].ToString();
}

让我知道留言箱的内容

编辑: 根据msdn:SqlDataAdapter.Fill()方法 ADDS 数据库中的值。 ==&GT;这个过程意味着为什么测试消息框总是随行增加。

我在上面的代码中添加了值,希望这有帮助