Binding data to a programmatically created DataTable

Suppose I have a datatable:

        DataTable dt = new DataTable("Woot");

        dt.Columns.AddRange(new DataColumn[]{
            new DataColumn("ID",typeof(System.Guid)),
            new DataColumn("Name",typeof(String))
            });

      

When I try to bind a control to it:

        this.txtName.DataBindings.Add("Text", _dtRow, "Name");

      

I am getting this exception:

Cannot bind property or column Name in data source. name parameter: dataMember

Any idea why this works on a datatable created by a dataAdapter but not programmatically created?

0


source to share


2 answers


Okay, after talking with your code for a while, I got confused all the time. Then I finally figured out the problem. I am assuming _dtRow is DataRow. You need to reference the actual DataTable (dt).

this.textBox1.DataBindings.Add("Text", dt, "Name");

      

EDIT: After seeing your comment on Igor's post. If you bind to dt say for example if you have datagridview associated with this DataTable every time you select a different row the textbox will change.

Here is the code that works for me:

            DataTable dt = new DataTable("Woot");

            dt.Columns.AddRange(new DataColumn[]{
            new DataColumn("ID",typeof(System.Guid)),
            new DataColumn("Name",typeof(String))
            });


            dt.Rows.Add(Guid.NewGuid(), "John");
            dt.Rows.Add(Guid.NewGuid(), "Jack");

            this.dataGridView1.DataSource = dt;

            this.textBox1.DataBindings.Add("Text", dt, "Name");

      



Change the lines in the DGV and you will see the text change text.

EIDT AGAIN Okay, time to crack. This is how I got it working:

this.textBox1.DataBindings.Add("Text",_dtRow.ItemArray[1], ""); 

      

I used index 1, but you can use whatever index you want in the array.

+3


source


Shouldn't you be referring to dt instead of _dtRow?

For example:

this.txtName.DataBindings.Add("Text", dt, "Name");

      



EDIT:

This code worked for me:

   DataTable dt = new DataTable("Woot");

    dt.Columns.AddRange(new DataColumn[]{
        new DataColumn("ID",typeof(System.Guid)),
        new DataColumn("Name",typeof(String))
    });

    DataRow r = dt.NewRow();
    r["ID"] = new Guid();
    r["Name"] = "AAA";
    dt.Rows.Add(r);

    r = dt.NewRow();
    r["ID"] = new Guid();
    r["Name"] = "BBB";
    dt.Rows.Add(r);

    dataGridView1.DataSource = dt;

    this.txtName.DataBindings.Add("Text", r.Table , "Name");

      

+1


source







All Articles