简体   繁体   English

C#绑定表中的特定行

[英]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. 使用c#.net 2.0,我想将文本框绑定到表的特定行。 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'. 我想将文本框绑定到该行包含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. 假设您正在谈论Winforms,并且您已经将数据源作为表单上的组件,这非常简单。

Drag a new BindingSource onto your form and set its data source to be whatever your existing data source is. 将一个新的BindingSource拖到您的窗体上,并将其数据源设置为您现有的数据源。 You can then specify a filtering expression in the new BindingSource 's Filter property in the designer. 然后,您可以在设计Filter的新BindingSourceFilter属性中指定过滤表达式。 Bind your TextBox to your new BindingSource and you're all set. 将您的TextBox绑定到新的BindingSource ,就一切BindingSource

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? 但是我不认为您绑定到TextBox吗? You can set the Text property like: 您可以将Text属性设置为:

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: 我将假定它是Winforms,这是您可以执行的操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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