Value ComboBox 在 C# 中更改 TextBox 的值

Value ComboBox Change Value Of TextBox In C#

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

(Conversion failed when converting the varchar value 'System.Data.DataRowView' to data type int)

代码是组合框 select 值更改文本框,包含此值的详细信息提前谢谢你。

 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();
    }

我认为你的 SqlDataAdapter 有问题:

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

应该是

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

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

额外:在声明其 data/value 成员后设置组合框数据源:

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 数据库中的值。 ==> 这当然意味着为什么测试消息框总是随着行数增加。

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