Refreshing text box from a bindingsource from an SQL query
I want to wire a text box to a BindingSource
. I tried this:
SqlDataAdapter da = new Sql开发者_高级运维DataAdapter("select col1, col2, from table1", conn);
DataSet dt = new DataSet();
da.Fill(dt);
bindingSource1.DataSource = dt;
textBox2.DataBindings.Add("Text", bindingSource1, "col1");
When I run it, it says this: Cannot bind to the property or column col1 on the DataSource. What am I doing wrong?
Try something like this:
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;
}
精彩评论