C# – Can’t bind a TextBox to a BindingSource

bindingsourcecsqlwinforms

I cannot seem to bind to a TextBox. Here is my source:

public partial class formAirFreightLabels : Form
{
    int pfDeclarationUID = -1;
    BindingNavigator bindingNavigatorMain = new BindingNavigator();
    BindingSource bindingSourceMain = new BindingSource();

    public formAirFreightLabels(int pvDeclarationUID)
    {
        InitializeComponent();
        pfDeclarationUID = pvDeclarationUID;

        this.bindingNavigatorMain.BindingSource = this.bindingSourceMain;
        this.bindingNavigatorMain.Dock = DockStyle.Bottom;
        this.Controls.Add(this.bindingNavigatorMain);

        this.Load += new EventHandler(formAirFreightLabels_Load);
    }

    void formAirFreightLabels_Load(object sender, EventArgs e)
    {
        SqlConnection cn = Program.GetSQLConnection();
        if (cn != null)
        {
            SqlCommand cmd = new SqlCommand(String.Format("SELECT ShipperName, ShipperAddress, ConsigneeName, ConsigneeAddress FROM Declarations WHERE DeclarationUID={0}", pfDeclarationUID), cn);
            SqlDataReader r = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            DataSet ds = new DataSet("Declarations");
            ds.Load(r, LoadOption.OverwriteChanges, new string[] { "Declarations" });
            bindingSourceMain.DataSource = ds;
            textBoxShipperName.DataBindings.Add(new Binding("Text", bindingSourceMain, "ShipperName", true));
        }
    }
}

I keep getting a run-time error as follows:

Cannot bind to the property or column ShipperName on the DataSource.
Parameter name: dataMember

Best Answer

As msdn says, you need to add TableName.ColumnName in order bind the controls. Windows Form Binding , you may try like this.

textBoxShipperName.DataBindings.Add(new Binding("Text", bindingSourceMain, "Declarations.ShipperName", true))
Related Topic