Control.BindingContext 属性 [C#]请参见 Control 类 | Control 成员 | System.Windows.Forms 命名空间 | BindingContextChanged | Binding | BindingManagerBase | 数据绑定和 Windows 窗体 | 在 Windows 窗体上创建简单绑定控件 | Control 成员(Visual J# 语法) | C++ 托管扩展编程 要求 平台: Windows 98, Windows NT 4.0, Windows ME, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 系列, .NET Framework 精简版 - Windows CE .NET 语言 C# Visual Basic 全部显示 获取或设置控件的 BindingContext。 [Visual Basic] Public Overridable Property BindingContext As BindingContext [C#] public virtual BindingContext BindingContext {get; set;} 属性值 控件的 BindingContext。 备注 Control 的 BindingContext 对象用于为 Control 包含的所有数据绑定控件返回单个 BindingManagerBase 对象。BindingManagerBase 对象使绑定到同一数据源的所有控件保持同步。例如,设置 BindingManagerBase 的 Position 属性将指定所有数据绑定控件所指向的基础列表中的项。有关创建新的 BindingContext 以及将它分配到 BindingContext 属性的更多信息,请参见 BindingContext。对继承者的说明: 在派生类中重写 BindingContext 属性时,请使用基类的 BindingContext 属性来扩展基实现。否则,您必须提供所有实现。不需要同时重写 BindingContext 属性的 get 和 set 访问器;如果需要,可以只重写其中一个访问器。示例 [Visual Basic, C#, C++] 下面的示例创建四个 Binding 对象,绑定到五个控件,一个 DateTimePicker 和四个 TextBox 控件,绑定到多个数据源。然后使用 BindingContext 为每个数据源获取 BindingManagerBase。[C#] protected void BindControls() { /* Create two Binding objects for the first two TextBox controls. The data-bound property for both controls is the Text property. The data source is a DataSet (ds). The data member is a navigation path in the form: "TableName.ColumnName". */ text1.DataBindings.Add(new Binding ("Text", ds, "customers.custName")); text2.DataBindings.Add(new Binding ("Text", ds, "customers.custID"));
/* Bind the DateTimePicker control by adding a new Binding. The data member of the DateTimePicker is a navigation path: TableName.RelationName.ColumnName string. */ DateTimePicker1.DataBindings.Add(new Binding("Value", ds, "customers.CustToOrders.OrderDate")); /* Add event delegates for the Parse and Format events to a new Binding object, and add the object to the third TextBox control's BindingsCollection. The delegates must be added before adding the Binding to the collection; otherwise, no formatting occurs until the Current object of the BindingManagerBase for the data source changes. */ Binding b = new Binding ("Text", ds, "customers.custToOrders.OrderAmount"); b.Parse+=new ConvertEventHandler(CurrencyStringToDecimal); b.Format+=new ConvertEventHandler(DecimalToCurrencyString); text3.DataBindings.Add(b); // Get the BindingManagerBase for the Customers table. bmCustomers = this.BindingContext [ds, "Customers"]; /* Get the BindingManagerBase for the Orders table using the RelationName. */ bmOrders = this.BindingContext[ds, "customers.CustToOrders"]; /* Bind the fourth TextBox control's Text property to the third control's Text property. */ text4.DataBindings.Add("Text", text3, "Text"); }要求 平台: Windows 98, Windows NT 4.0, Windows ME, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 系列, .NET Framework 精简版 - Windows CE .NET
把该列绑定到ComboBox上,方法如下: 把如下类放入你的名称空间 using System; using System.Windows.Forms; using System.Drawing; using System.Data; using System.Diagnostics;namespace 你的名称空间 { // Derive class from DataGridTextBoxColumn public class DataGridComboBoxColumn : DataGridTextBoxColumn { // Hosted ComboBox control private ComboBox comboBox; private CurrencyManager cm; private int iCurrentRow;
// Constructor - create combobox, register selection change event handler, // register lose focus event handler public DataGridComboBoxColumn() { this.cm = null; // Create ComboBox and force DropDownList style this.comboBox = new ComboBox(); this.comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
// Add event handler for notification of when ComboBox loses focus this.comboBox.Leave += new EventHandler(comboBox_Leave); }
// Property to provide access to ComboBox public ComboBox ComboBox { get { return comboBox; } }
// On edit, add scroll event handler, and display combo box protected override void Edit(System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Rectangle bounds, bool readOnly, string instantText, bool cellIsVisible) { Debug.WriteLine(String.Format("Edit {0}", rowNum)); base.Edit(source, rowNum, bounds, readOnly, instantText, cellIsVisible); if (!readOnly && cellIsVisible) { // Save current row in the datagrid and currency manager associated with // the data source for the datagrid this.iCurrentRow = rowNum; this.cm = source;
// Add event handler for datagrid scroll notification this.DataGridTableStyle.DataGrid.Scroll += new EventHandler(DataGrid_Scroll); // Site the combo box control within the bounds of the current cell this.comboBox.Parent = this.TextBox.Parent; Rectangle rect = this.DataGridTableStyle.DataGrid.GetCurrentCellBounds(); this.comboBox.Location = rect.Location; this.comboBox.Size = new Size(this.TextBox.Size.Width, this.comboBox.Size.Height); // Set combo box selection to given text this.comboBox.SelectedIndex = this.comboBox.FindStringExact(this.TextBox.Text); // Make the ComboBox visible and place on top text box control this.comboBox.Show(); this.comboBox.BringToFront(); this.comboBox.Focus(); } } // Given a row, get the value member associated with a row. Use the value // member to find the associated display member by iterating over bound datasource protected override object GetColumnValueAtRow(System.Windows.Forms.CurrencyManager source, int rowNum) { Debug.WriteLine(String.Format("GetColumnValueAtRow {0}", rowNum)); // Given a row number in the datagrid, get the display member object obj = base.GetColumnValueAtRow(source, rowNum);
// Iterate through the datasource bound to the ColumnComboBox // Don't confuse this datasource with the datasource of the associated datagrid CurrencyManager cm = (CurrencyManager) (this.DataGridTableStyle.DataGrid.BindingContext[this.comboBox.DataSource]); // Assumes the associated DataGrid is bound to a DataView, or DataTable that // implements a default DataView DataView dataview = ((DataView)cm.List);
int i; for (i = 0; i < dataview.Count; i++) { if (obj.Equals(dataview[i][this.comboBox.ValueMember])) break; }
if (i < dataview.Count) return dataview[i][this.comboBox.DisplayMember];
return DBNull.Value; } // Given a row and a display member, iterating over bound datasource to find // the associated value member. Set this value member. protected override void SetColumnValueAtRow(System.Windows.Forms.CurrencyManager source, int rowNum, object value) { Debug.WriteLine(String.Format("SetColumnValueAtRow {0} {1}", rowNum, value)); object s = value; // Iterate through the datasource bound to the ColumnComboBox // Don't confuse this datasource with the datasource of the associated datagrid CurrencyManager cm = (CurrencyManager) (this.DataGridTableStyle.DataGrid.BindingContext[this.comboBox.DataSource]); // Assumes the associated DataGrid is bound to a DataView, or DataTable that // implements a default DataView DataView dataview = ((DataView)cm.List); int i; for (i = 0; i < dataview.Count; i++) { if (s.Equals(dataview[i][this.comboBox.DisplayMember])) break; } // If set item was found return corresponding value, otherwise return DbNull.Value if(i < dataview.Count) s = dataview[i][this.comboBox.ValueMember]; else s = DBNull.Value;
base.SetColumnValueAtRow(source, rowNum, s); } // On datagrid scroll, hide the combobox private void DataGrid_Scroll(object sender, EventArgs e) { Debug.WriteLine("Scroll"); this.comboBox.Hide(); } // On combo box losing focus, set the column value, hide the combo box, // and unregister scroll event handler private void comboBox_Leave(object sender, EventArgs e) { DataRowView rowView = (DataRowView) this.comboBox.SelectedItem; string s = (string) rowView.Row[this.comboBox.DisplayMember]; Debug.WriteLine(String.Format("Leave: {0} {1}", this.comboBox.Text, s)); SetColumnValueAtRow(this.cm, this.iCurrentRow, s); Invalidate(); this.comboBox.Hide(); this.DataGridTableStyle.DataGrid.Scroll -= new EventHandler(DataGrid_Scroll); } } } 在你的含有DataGrid的FORM中(假定要变换的列为dataGridTextBoxColumn4)作如下改动: //变量声明部分 private DataGridComboBoxColumn dataGridTextBoxColumn4; //在private void InitializeComponent()中: this.dataGridTextBoxColumn4 = new TySurvey.DataGridComboBoxColumn(); //创建一表"NameTable"存放变换关系: 00001对应A公司,00002对应B公司,00003对应C公司 //npk对应:00001、00002、00003 //vcName对应:A公司,B公司,C公司//在Load事件中填加 dataGridTextBoxColumn4.ComboBox.DataSource = ds1.Tables["NameTable"]; dataGridTextBoxColumn4.ComboBox.DisplayMember = "vcName"; dataGridTextBoxColumn4.ComboBox.ValueMember = "nPK";
一个完整的函数 string strCon =" Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = dms.mdb " ; OleDbConnection myConn = new OleDbConnection(strCon); try { myConn.Open(); string strSele = " SELECT code FROM device_code ORDER BY code"; DataSet myDataSet = new DataSet ( ) ; OleDbCommand myCommand = new OleDbCommand ( strSele , myConn ) ; OleDbDataReader DbReader = myCommand.ExecuteReader(); while(DbReader.Read()) { this.comDeviCode.Items.Add(DbReader.GetString(0)); } } catch ( Exception ee ) { MessageBox.Show ( "连接数据库发生错误为:" + ee.ToString ( ) , "错误!" ) ; }
...
private DataTable dt_Main=null;
private DataTable dt_Detail=null;
private Eps.Controls.WinControls.TextComboBox cb_ZTBJ=
new Eps.Controls.WinControls.TextComboBox();
...
private void Ctrls_TextChanged(object sender,System.EventArgs e)
{
try
{
if(dgMain.CurrentCell.ColumnNumber==dt_Main.Columns.IndexOf("狀態標記"))
{
cb_ZTBJ.Visible=false;
dgMain[dgMain.CurrentCell]=cb_ZTBJ.Text;
}
}
catch
{
}
} private void GetBillData()
{
if(txtDjlb.Text=="" || txtDjbh.Text=="")
return;
cb_ZTBJ.Height=20;
cb_ZTBJ.TextChanged+=new System.EventHandler(this.Ctrls_TextChanged);
cb_ZTBJ.Items.Clear();
cb_ZTBJ.Items.Add("NoConfirm");
cb_ZTBJ.Items.Add("Confirm");
cb_ZTBJ.Items.Add("Checking");
cb_ZTBJ.Items.Add("Complete");
cb_ZTBJ.SelectedIndex=0; dt_Main=UsualProcess.GetBillData(txtDjlb.Text,txtDjbh.Text,0);
dgMain.PreferredRowHeight=cb_ZTBJ.Height;
dgMain.DataSource=dt_Main.DefaultView;
if(XB!="" && XBZD!="")
{
dt_Detail=UsualProcess.GetBillData(txtDjlb.Text,txtDjbh.Text,1);
dgDetail.DataSource =dt_Detail.DefaultView;
}
else
{
dt_Detail=null;
dgDetail.DataSource=dt_Detail;
}
dgMain.Controls.Add(cb_ZTBJ);
} private void dgMain_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
try
{
if(dgMain.CurrentCell.ColumnNumber==dt_Main.Columns.IndexOf("狀態標記"))
{
cb_ZTBJ.Width=dgMain.GetCurrentCellBounds().Width;
}
}
catch
{
}
} private void dgMain_CurrentCellChanged(object sender, System.EventArgs e)
{
if(dgMain.CurrentCell.ColumnNumber==dt_Main.Columns.IndexOf("狀態標記"))
{
cb_ZTBJ.Visible=false;
cb_ZTBJ.Width=0;
cb_ZTBJ.Left=dgMain.GetCurrentCellBounds().Left;
cb_ZTBJ.Top=dgMain.GetCurrentCellBounds().Top;
cb_ZTBJ.Text=Convert.ToString(dgMain[dgMain.CurrentCell]);
cb_ZTBJ.Visible=true;
}
else
{
cb_ZTBJ.Visible=false;
cb_ZTBJ.Width=0;
}
} private void dgMain_Scroll(object sender, System.EventArgs e)
{
cb_ZTBJ.Visible=false;
cb_ZTBJ.Width=0;
} private void dgMain_Click(object sender, System.EventArgs e)
{
cb_ZTBJ.Visible=false;
cb_ZTBJ.Width=0;
}
Control 类 | Control 成员 | System.Windows.Forms 命名空间 | BindingContextChanged | Binding | BindingManagerBase | 数据绑定和 Windows 窗体 | 在 Windows 窗体上创建简单绑定控件 | Control 成员(Visual J# 语法) | C++ 托管扩展编程
要求
平台: Windows 98, Windows NT 4.0, Windows ME, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 系列, .NET Framework 精简版 - Windows CE .NET
语言
C#
Visual Basic
全部显示
获取或设置控件的 BindingContext。
[Visual Basic]
Public Overridable Property BindingContext As BindingContext
[C#]
public virtual BindingContext BindingContext {get; set;}
属性值
控件的 BindingContext。
备注
Control 的 BindingContext 对象用于为 Control 包含的所有数据绑定控件返回单个 BindingManagerBase 对象。BindingManagerBase 对象使绑定到同一数据源的所有控件保持同步。例如,设置 BindingManagerBase 的 Position 属性将指定所有数据绑定控件所指向的基础列表中的项。有关创建新的 BindingContext 以及将它分配到 BindingContext 属性的更多信息,请参见 BindingContext。对继承者的说明: 在派生类中重写 BindingContext 属性时,请使用基类的 BindingContext 属性来扩展基实现。否则,您必须提供所有实现。不需要同时重写 BindingContext 属性的 get 和 set 访问器;如果需要,可以只重写其中一个访问器。示例
[Visual Basic, C#, C++] 下面的示例创建四个 Binding 对象,绑定到五个控件,一个 DateTimePicker 和四个 TextBox 控件,绑定到多个数据源。然后使用 BindingContext 为每个数据源获取 BindingManagerBase。[C#]
protected void BindControls()
{
/* Create two Binding objects for the first two TextBox
controls. The data-bound property for both controls
is the Text property. The data source is a DataSet
(ds). The data member is a navigation path in the form:
"TableName.ColumnName". */
text1.DataBindings.Add(new Binding
("Text", ds, "customers.custName"));
text2.DataBindings.Add(new Binding
("Text", ds, "customers.custID"));
/* Bind the DateTimePicker control by adding a new Binding.
The data member of the DateTimePicker is a navigation path:
TableName.RelationName.ColumnName string. */
DateTimePicker1.DataBindings.Add(new
Binding("Value", ds, "customers.CustToOrders.OrderDate")); /* Add event delegates for the Parse and Format events to a
new Binding object, and add the object to the third
TextBox control's BindingsCollection. The delegates
must be added before adding the Binding to the
collection; otherwise, no formatting occurs until
the Current object of the BindingManagerBase for
the data source changes. */
Binding b = new Binding
("Text", ds, "customers.custToOrders.OrderAmount");
b.Parse+=new ConvertEventHandler(CurrencyStringToDecimal);
b.Format+=new ConvertEventHandler(DecimalToCurrencyString);
text3.DataBindings.Add(b); // Get the BindingManagerBase for the Customers table.
bmCustomers = this.BindingContext [ds, "Customers"]; /* Get the BindingManagerBase for the Orders table using the
RelationName. */
bmOrders = this.BindingContext[ds, "customers.CustToOrders"]; /* Bind the fourth TextBox control's Text property to the
third control's Text property. */
text4.DataBindings.Add("Text", text3, "Text");
}要求
平台: Windows 98, Windows NT 4.0, Windows ME, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 系列, .NET Framework 精简版 - Windows CE .NET
http://www.syncfusion.com/FAQ/WinForms/FAQ_c44c.asp#q480q
然后把数据库中的一列取出来放到一个表中。如:table1
然后进行帮定
this.combobox1.DataSource=table1
this.combobox1.Displaymember="列名"
this.combobox1.Valuemember="列名"当然还有其他的方法 如果有兴趣的话 可以在聊
把如下类放入你的名称空间
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data;
using System.Diagnostics;namespace 你的名称空间
{
// Derive class from DataGridTextBoxColumn
public class DataGridComboBoxColumn : DataGridTextBoxColumn
{
// Hosted ComboBox control
private ComboBox comboBox;
private CurrencyManager cm;
private int iCurrentRow;
// Constructor - create combobox, register selection change event handler,
// register lose focus event handler
public DataGridComboBoxColumn()
{
this.cm = null; // Create ComboBox and force DropDownList style
this.comboBox = new ComboBox();
this.comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
// Add event handler for notification of when ComboBox loses focus
this.comboBox.Leave += new EventHandler(comboBox_Leave);
}
// Property to provide access to ComboBox
public ComboBox ComboBox
{
get { return comboBox; }
}
// On edit, add scroll event handler, and display combo box
protected override void Edit(System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Rectangle bounds, bool readOnly, string instantText, bool cellIsVisible)
{
Debug.WriteLine(String.Format("Edit {0}", rowNum));
base.Edit(source, rowNum, bounds, readOnly, instantText, cellIsVisible); if (!readOnly && cellIsVisible)
{
// Save current row in the datagrid and currency manager associated with
// the data source for the datagrid
this.iCurrentRow = rowNum;
this.cm = source;
// Add event handler for datagrid scroll notification
this.DataGridTableStyle.DataGrid.Scroll += new EventHandler(DataGrid_Scroll); // Site the combo box control within the bounds of the current cell
this.comboBox.Parent = this.TextBox.Parent;
Rectangle rect = this.DataGridTableStyle.DataGrid.GetCurrentCellBounds();
this.comboBox.Location = rect.Location;
this.comboBox.Size = new Size(this.TextBox.Size.Width, this.comboBox.Size.Height); // Set combo box selection to given text
this.comboBox.SelectedIndex = this.comboBox.FindStringExact(this.TextBox.Text); // Make the ComboBox visible and place on top text box control
this.comboBox.Show();
this.comboBox.BringToFront();
this.comboBox.Focus();
}
} // Given a row, get the value member associated with a row. Use the value
// member to find the associated display member by iterating over bound datasource
protected override object GetColumnValueAtRow(System.Windows.Forms.CurrencyManager source, int rowNum)
{
Debug.WriteLine(String.Format("GetColumnValueAtRow {0}", rowNum));
// Given a row number in the datagrid, get the display member
object obj = base.GetColumnValueAtRow(source, rowNum);
// Iterate through the datasource bound to the ColumnComboBox
// Don't confuse this datasource with the datasource of the associated datagrid
CurrencyManager cm = (CurrencyManager)
(this.DataGridTableStyle.DataGrid.BindingContext[this.comboBox.DataSource]);
// Assumes the associated DataGrid is bound to a DataView, or DataTable that
// implements a default DataView
DataView dataview = ((DataView)cm.List);
int i; for (i = 0; i < dataview.Count; i++)
{
if (obj.Equals(dataview[i][this.comboBox.ValueMember]))
break;
}
if (i < dataview.Count)
return dataview[i][this.comboBox.DisplayMember];
return DBNull.Value;
} // Given a row and a display member, iterating over bound datasource to find
// the associated value member. Set this value member.
protected override void SetColumnValueAtRow(System.Windows.Forms.CurrencyManager source, int rowNum, object value)
{
Debug.WriteLine(String.Format("SetColumnValueAtRow {0} {1}", rowNum, value));
object s = value; // Iterate through the datasource bound to the ColumnComboBox
// Don't confuse this datasource with the datasource of the associated datagrid
CurrencyManager cm = (CurrencyManager)
(this.DataGridTableStyle.DataGrid.BindingContext[this.comboBox.DataSource]);
// Assumes the associated DataGrid is bound to a DataView, or DataTable that
// implements a default DataView
DataView dataview = ((DataView)cm.List);
int i; for (i = 0; i < dataview.Count; i++)
{
if (s.Equals(dataview[i][this.comboBox.DisplayMember]))
break;
} // If set item was found return corresponding value, otherwise return DbNull.Value
if(i < dataview.Count)
s = dataview[i][this.comboBox.ValueMember];
else
s = DBNull.Value;
base.SetColumnValueAtRow(source, rowNum, s);
} // On datagrid scroll, hide the combobox
private void DataGrid_Scroll(object sender, EventArgs e)
{
Debug.WriteLine("Scroll");
this.comboBox.Hide();
} // On combo box losing focus, set the column value, hide the combo box,
// and unregister scroll event handler
private void comboBox_Leave(object sender, EventArgs e)
{
DataRowView rowView = (DataRowView) this.comboBox.SelectedItem;
string s = (string) rowView.Row[this.comboBox.DisplayMember];
Debug.WriteLine(String.Format("Leave: {0} {1}", this.comboBox.Text, s)); SetColumnValueAtRow(this.cm, this.iCurrentRow, s);
Invalidate(); this.comboBox.Hide();
this.DataGridTableStyle.DataGrid.Scroll -= new EventHandler(DataGrid_Scroll);
}
}
}
在你的含有DataGrid的FORM中(假定要变换的列为dataGridTextBoxColumn4)作如下改动:
//变量声明部分
private DataGridComboBoxColumn dataGridTextBoxColumn4;
//在private void InitializeComponent()中:
this.dataGridTextBoxColumn4 = new TySurvey.DataGridComboBoxColumn();
//创建一表"NameTable"存放变换关系: 00001对应A公司,00002对应B公司,00003对应C公司
//npk对应:00001、00002、00003
//vcName对应:A公司,B公司,C公司//在Load事件中填加
dataGridTextBoxColumn4.ComboBox.DataSource = ds1.Tables["NameTable"];
dataGridTextBoxColumn4.ComboBox.DisplayMember = "vcName";
dataGridTextBoxColumn4.ComboBox.ValueMember = "nPK";
string strCon =" Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = dms.mdb " ;
OleDbConnection myConn = new OleDbConnection(strCon);
try
{
myConn.Open();
string strSele = " SELECT code FROM device_code ORDER BY code";
DataSet myDataSet = new DataSet ( ) ;
OleDbCommand myCommand = new OleDbCommand ( strSele , myConn ) ;
OleDbDataReader DbReader = myCommand.ExecuteReader();
while(DbReader.Read())
{
this.comDeviCode.Items.Add(DbReader.GetString(0));
}
}
catch ( Exception ee )
{
MessageBox.Show ( "连接数据库发生错误为:" + ee.ToString ( ) , "错误!" ) ;
}
主要是写datagrid里面的paint和CurrentCellChanged事件!
paint中:
if (dataGrid.CurrentCell.ColumnNumber == 0)//第一列
{
comboBox1.Width=dataGrid.GetCurrentCellBounds().Width;
}
CurrentCellChanged中标:
if (dataGrid.CurrentCell.ColumnNumber == 0)
{
comboBox1.Width =0;
comboBox1.Left = dataGrid.GetCurrentCellBounds().Left ;
comboBox1.Top = dataGrid.GetCurrentCellBounds ().Top ;
}
这样就可以实现下拉选择了!
至于要和第二列实现对应关系,你可以设置数组来实现的,比较简单
相信你应该可以摆平!
combobox中的TextChanged中:
if (dataGridSchedule.CurrentCell.ColumnNumber == 0)
{
dataGrid[dataGrid.CurrentCell] =comboBox.Text ;
}