从SQL查询中的绑定源刷新文本框

时间:2011-03-10 14:33:33

标签: c# sql bindingsource

我想将文本框连接到BindingSource。我试过这个:

            SqlDataAdapter da = new SqlDataAdapter("select col1, col2, from table1", conn);
            DataSet dt = new DataSet();
            da.Fill(dt);

            bindingSource1.DataSource = dt;

            textBox2.DataBindings.Add("Text", bindingSource1, "col1");

当我运行它时,它说:     无法绑定到DataSource上的属性或列col1。 我做错了什么?

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

BindingSource _bs;


private void Form1_Load(object sender, System.EventArgs e) {
    //  Creamos el objeto BindingSource
    _bs = new BindingSource();
    //  Establecemos la conexi?n para recuperar los datos
    //  de los Clientes.
    // 
    SqlConnection cnn = new SqlConnection("Data Source=(local);");
    string sql = "SELECT * FROM Clientes";
    SqlDataAdapter da = new SqlDataAdapter(sql, cnn);
    DataSet ds = new DataSet();
    //  Rellenamos el objeto DataSet
    da.Fill(ds, "Clientes");
    //  Le asignamos el origen de datos al objeto BindingSource
    // 
    _bs.DataSource = ds;
    //  Objeto DataSet
    _bs.DataMember = "Clientes";
    TextBox1.DataBindings.Add("Text", _bs, "IdCliente");
    TextBox2.DataBindings.Add("Text", _bs, "Nombre");
    //  Enlazamos el control BindingNavigator
    // 
    BindingNavigator1.BindingSource = _bs;
}