繁体   English   中英

值ComboBox更改C#中TextBox的值

[英]Value ComboBox Change Value Of TextBox In C#

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

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

代码是combobox选择值更改文本框,其中包含该值的详细信息并预先感谢您。

 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。

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

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数据库内部的值。 ==>当然,这意味着测试消息框总是随行增加的原因。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM