简体   繁体   中英

c# Binding on specific row in table

Using c# .net 2.0 , I want to bind a textbox to a specific row of my table. In Example :

 Table Person
 ID NAME PRENOM SPECIAL_CATEGORY
  1 BOB  BOB    mex
  2 AL   AL     tot
  3 PO   PO     pap

I want to bind my textbox on the field name where the row contains special_categeory = 'tot'. Is it possible? or I need to create a Datarow for this row and binding it.

Assuming you're talking about Winforms and you have your data source as a component on your form already, this is fairly simple.

Drag a new BindingSource onto your form and set its data source to be whatever your existing data source is. You can then specify a filtering expression in the new BindingSource 's Filter property in the designer. Bind your TextBox to your new BindingSource and you're all set.

Doing this manually (without the designer) is only marginally more complicated.

BindingSource newSource = new BindingSource();

newSource.DataSource = yourExistingDataSource;
newSource.Filter = "special_categeory = 'tot'";

textBox.DataBindings.Add("Text", newSource, "DataMember");

You should be able to bind via...

myNameTextBox.DataBindings.Add( "Text", MyTable, "NAME" );
myPrenomTextBox.DataBindings.Add( "Text", MyTable, "PRENOM" );
mySpecial_CategoryTextBox.DataBindings.Add( "Text", MyTable, "SPECIAL_CATEGORY" );

I actually have a framework that scrolls through all controls, and if they match a column name in a given table, they immediately bind themselves like above.

Then, when you scroll the grid, it should also refresh the individual text controls in your form too.

If there is some binding that needs to be done, you can follow this pattern:

DataView dv = new DataView(MyTable);
dv.RowFilter = "SPECIAL_CATEGORY = 'tot'";
GridView1.DataSource = dv;
GridView1.DataBind();

But I don't think you bind to a TextBox? You can set the Text property like:

foreach(DataRow dr in MyTable.Rows)
{
    if (dr["SPECIAL_CATEGORY"] != DBNull.Value &&
          dr["SPECIAL_CATEGORY"].ToString() == "tot")
    {
       myTextBox.Text = dr["NAME"].ToString()
       break;
    }
}

I'm going to assume it's Winforms and this is how you can do it:

myTable.DefaultView.RowFilter = "SPECIAL_CATEGORY = 'tot'";
this.textBox1.DataBindings.Add("Text",myTable.DefaultView,"Name");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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