WinForm数据绑定

合集下载

winform中的ListBox和ComboBox绑定数据用法实例

winform中的ListBox和ComboBox绑定数据用法实例
希望本文所述对大家的C#程序设计有所帮助。
本例实现将集合数据绑定到ListBox和ComboBox控件,界面上显示某个属性的内容,代码如下:
复制代码 代码如下:
//... //自定义了Person类(有Name,Age,Heigth等属性)
List<Person> persons=new List<Person>(); persons.Add(new Person("WuMiao",18,175)); persons.Add(new Person("YeXinYv",20,170)); persons.Add(new Person("WuDong",18,175));
arraylist是接口list的实现类所以在使用过程中比较推荐使用list接口来实现arraylist在程序开发过程中应用非常广泛接下来脚本之家的小编给大家总结了arraylist的使用有需要的朋友可以参考下
winform中的 ListBox和 ComboBox绑定数据用法实例
本文实例讲述了winform中的ListBox和ComboBox绑定数据用法。分享给大家供大家参考。具体实现方法如下:
//ListBox控件实现 lb_PersonsList.DataSource=persons; //指定数据源 lb_PersonList.DisplayMember="Name"; //界面显示的是人的名字
//ComboBox控件实现 (与Le=persons; cmb_PersonList.DisplayMember="Name";

winform中的TreeView的数据绑定

winform中的TreeView的数据绑定

winform中的TreeView的数据绑定#region绑定TreeView///<summary>///绑定TreeView(利⽤TreeNode)///</summary>///<param name="p_Node">TreeNode(TreeView的⼀个节点)</param>///<param name="pid_val">⽗id的值</param>///<param name="id">数据库 id 字段名</param>///<param name="pid">数据库⽗id 字段名</param>///<param name="text">数据库⽂本字段值</param>protected void Bind_Tv(DataTable dt, TreeNode p_Node, string pid_val, string id, string pid, string text){DataView dv = new DataView(dt);//将DataTable存到DataView中,以便于筛选数据TreeNode tn;//建⽴TreeView的节点(TreeNode),以便将取出的数据添加到节点中//以下为三元运算符,如果⽗id为空,则为构建“⽗id字段 is null”的查询条件,否则构建“⽗id字段=⽗id字段值”的查询条件string filter = string.IsNullOrEmpty(pid_val) ? pid + " is null" : string.Format(pid + "='{0}'", pid_val);dv.RowFilter = filter;//利⽤DataView将数据进⾏筛选,选出相同⽗id值的数据foreach (DataRowView row in dv){tn = new TreeNode();//建⽴⼀个新节点(学名叫:⼀个实例)if (p_Node == null)//如果为根节点{ = row[id].ToString();//节点的Value值,⼀般为数据库的id值tn.Text = row[text].ToString();//节点的Text,节点的⽂本显⽰TreeView1.Nodes.Add(tn);//将该节点加⼊到TreeView中Bind_Tv(dt, tn, , id, pid, text);//递归(反复调⽤这个⽅法,直到把数据取完为⽌)}else//如果不是根节点{ = row[id].ToString();//节点Value值tn.Text = row[text].ToString();//节点Text值p_Node.Nodes.Add(tn);//该节点加⼊到上级节点中Bind_Tv(dt, tn, , id, pid, text);//递归}}}///<summary>///绑定TreeView(利⽤TreeNodeCollection)///</summary>///<param name="tnc">TreeNodeCollection(TreeView的节点集合)</param>///<param name="pid_val">⽗id的值</param>///<param name="id">数据库 id 字段名</param>///<param name="pid">数据库⽗id 字段名</param>///<param name="text">数据库⽂本字段值</param>private void Bind_Tv(DataTable dt, TreeNodeCollection tnc, string pid_val, string id, string pid, string text){DataView dv = new DataView(dt);//将DataTable存到DataView中,以便于筛选数据TreeNode tn;//建⽴TreeView的节点(TreeNode),以便将取出的数据添加到节点中//以下为三元运算符,如果⽗id为空,则为构建“⽗id字段 is null”的查询条件,否则构建“⽗id字段=⽗id字段值”的查询条件string filter = string.IsNullOrEmpty(pid_val) ? pid + " is null" : string.Format(pid + "='{0}'", pid_val);dv.RowFilter = filter;//利⽤DataView将数据进⾏筛选,选出相同⽗id值的数据foreach (DataRowView drv in dv){tn = new TreeNode();//建⽴⼀个新节点(学名叫:⼀个实例) = drv[id].ToString();//节点的Value值,⼀般为数据库的id值tn.Text = drv[text].ToString();//节点的Text,节点的⽂本显⽰tnc.Add(tn);//将该节点加⼊到TreeNodeCollection(节点集合)中Bind_Tv(dt, tn.Nodes, , id, pid, text);//递归(反复调⽤这个⽅法,直到把数据取完为⽌)}}#endregion绑定代码:Bind_Tv(datatable,TreeView1.Nodes, null, "id字段", "⽗id字段", "名称字段");。

Winfrom中ListBox绑定List数据源更新问题

Winfrom中ListBox绑定List数据源更新问题
如果listbox的数据源是datatable是可以自动更新的但若是listt时对数据的修改界面不会更新使用bindingsource绑定就可以了
Winfrom中 ListBox绑定 List数据源更新问题
Winfrom中ListBox绑定List数据源,第一次可以成功,但后面List更新以后,ListBox并没有更新。
如果 ListBox的数据源 是 DataTable 是可以自动更新的,但若是 List<T> 时对数据的修改界面不会更新,使用 BindingSource 绑定就可以 了。 private void InitSample() { ListBox listControl = new ListBox(); List<Employee> listSource = new List<Employee>(); BindingSource bs = new BindingSource(); bs.DataSource = listSource;
this.Controls.Adห้องสมุดไป่ตู้(listControl); }
补充:使用BindingList亦可解决此问题!
listControl.DataSource = bs; listControl.DisplayMember = “Name”; listControl.ValueMember = “Id”;
// 事先绑定了,这时修改数据源会自动刷新界面显示 listSource.Add(new Employee(1, “Sam”)); listSource.Add(new Employee(2, “John”));

C#winformDataGridView绑定数据的的几种方法

C#winformDataGridView绑定数据的的几种方法

C#winformDataGridView绑定数据的的⼏种⽅法1.⽤DataSet和DataTable为DataGridView提供数据源String strConn = "Data Source=.;Initial Catalog=His;User ID=sa;Password=*****";SqlConnection conn = new SqlConnection(strConn);String sql= "select * from EMPLOYEE ";conn.Open();SqlCommand cmd = new SqlCommand(sqlId, conn);SqlDataAdapter da = new SqlDataAdapter(cmd);DataSet ds = new DataSet();da.Fill(ds, "EMPLOYEE");dataGridView1.DataSource = ds;this.dataGridView1.AutoGenerateColumns = false;//是否⾃动⽣成列dataGridView1.DataMember = "EMPLOYEE";conn.Close();2.创建DataGridViewRow 对象Add添加⾏String sql_conn= "Data Source=.;Initial Catalog=His;User ID=sa;Password=*****";System.Data.DataTable table =return_table(sql_conn);foreach (System.Data.DataRow date in table.Rows){DataGridViewRow newRow = new DataGridViewRow();newRow.CreateCells(this.dataGridView1);newRow.Cells[0].Value = date[0].ToString();newRow.Cells[1].Value = date[1].ToString();newRow.Cells[2].Value = date[2].ToString();newRow.Cells[3].Value = date[3].ToString();newRow.Cells[4].Value = date[4].ToString();dataGridView1.Rows.Add(newRow);}public System.Data.DataTable return_table(string sql_conn){SqlConnection conn = new SqlConnection(sql_conn);SqlDataReader reader = null;conn.Open();SqlCommand command = new SqlCommand("selectRegID,Name,Area,RoomNO,BedNO from EMPLOYEE", conn);reader = command.ExecuteReader();return ConvertToDataTable(reader);}public DataTable ConvertToDataTable(SqlDataReader dataReader)//SqlDataReader转换为DataTable{DataTable dt = new DataTable();DataTable schemaTable = dataReader.GetSchemaTable();try{//动态构建表,添加列foreach (DataRow dr in schemaTable.Rows){DataColumn dc = new DataColumn();//设置列的数据类型dc.DataType = dr[0].GetType();//设置列的名称dc.ColumnName = dr[0].ToString();//将该列添加进构造的表中dt.Columns.Add(dc);}//读取数据添加进表中while (dataReader.Read()){DataRow row = dt.NewRow();//填充⼀⾏数据for (int i = 0; i < schemaTable.Rows.Count; i++){row[i] = dataReader[i].ToString();}dt.Rows.Add(row);row = null;}dataReader.Close();schemaTable = null;return dt;}catch (Exception ex){//抛出异常throw new Exception(ex.Message); }}。

ItemsControl数据绑定的两种方式

ItemsControl数据绑定的两种方式

ItemsControl数据绑定的两种⽅式最近在学习ItemsControl这个控件的时候,查看了MSDN上⾯的⼀个例⼦,并且⾃⼰做了⼀些修改,这⾥主要使⽤了两种⽅式来进⾏相应的数据绑定,⼀种是使⽤DataContext,另外⼀种是直接将⼀个类绑定到前台,其实这两种⽅式原理差不多都是将数据模型的对象添加到⼀个ObservableCollection集合中,然后再绑定到前台,下⾯分别介绍两种绑定⽅式:第⼀种是将数据存储在⼀个ObservableCollection集合中,然后作为ItemsControl的DataContext对象,下⾯分别贴出相关的代码:<Window x:Class="TestGrid.MainWindow"xmlns="/winfx/2006/xaml/presentation"xmlns:x="/winfx/2006/xaml"xmlns:local="clr-namespace:TestGrid"Title="MainWindow" Height="350" Width="525"><Grid><ItemsControl Margin="10" x:Name="myItemsControl" ItemsSource="{Binding}"><ItemsControl.Template><ControlTemplate TargetType="ItemsControl"><Border BorderBrush="Aqua" BorderThickness="1" CornerRadius="15"><ItemsPresenter/></Border></ControlTemplate></ItemsControl.Template><ItemsControl.ItemsPanel><ItemsPanelTemplate><WrapPanel/></ItemsPanelTemplate></ItemsControl.ItemsPanel><ItemsControl.ItemTemplate><DataTemplate DataType="{ x:Type local:DataSource}"><DataTemplate.Resources><Style TargetType="TextBlock"><Setter Property="FontSize" Value="18"/><Setter Property="HorizontalAlignment" Value="Center"/></Style></DataTemplate.Resources><Grid><Rectangle Fill="Green"/><Ellipse Fill="Red"/><StackPanel><TextBlock Margin="3,3,3,0" Text="{Binding Path=Priority,Mode=TwoWay}"/><TextBlock Margin="3,0,3,7" Text="{Binding Path=TaskName,Mode=TwoWay}"/></StackPanel></Grid></DataTemplate></ItemsControl.ItemTemplate><ItemsControl.ItemContainerStyle><Style><Setter Property="Control.Width" Value="100"/><Setter Property="Control.Margin" Value="5"/><Style.Triggers><Trigger Property="Control.IsMouseOver" Value="True"><Setter Property="Control.ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=Content.Description}"/></Trigger></Style.Triggers></Style></ItemsControl.ItemContainerStyle></ItemsControl></Grid></Window>这⾥需要注意的地⽅是 ItemsSource="{Binding}"这句必须添加,否则后台的数据是⽆法添加到前台的,这个需要注意,这⾥贴出后台的代码using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes;namespace TestGrid{/// <summary>/// MainWindow.xaml 的交互逻辑/// </summary>public partial class MainWindow : Window{private ObservableCollection<DataSource> item = null; public MainWindow(){InitializeComponent();item = new ObservableCollection<DataSource>();item.Add(new DataSource(){Priority = "1",TaskName = "hello"});item.Add(new DataSource(){Priority = "2",TaskName = "whats"});item.Add(new DataSource(){Priority = "3",TaskName = "your"});item.Add(new DataSource(){Priority = "4",TaskName = "name"});item.Add(new DataSource(){Priority = "5",TaskName = "can"});item.Add(new DataSource(){Priority = "6",TaskName = "you"});this.myItemsControl.DataContext = item;}}}using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes;namespace TestGrid{/// <summary>/// MainWindow.xaml 的交互逻辑/// </summary>public partial class MainWindow : Window{private ObservableCollection<DataSource> item = null; public MainWindow(){InitializeComponent();item = new ObservableCollection<DataSource>();item.Add(new DataSource(){Priority = "1",TaskName = "hello"});item.Add(new DataSource(){Priority = "2",TaskName = "whats"});item.Add(new DataSource(){Priority = "3",TaskName = "your"});item.Add(new DataSource(){Priority = "4",TaskName = "name"});item.Add(new DataSource(){Priority = "5",TaskName = "can"});item.Add(new DataSource(){Priority = "6",TaskName = "you"});this.myItemsControl.DataContext = item;}}}这⾥最重要的⼀句就是 this.myItemsControl.DataContext = item;这个是将刚才的集合绑定到ItemsControl控件上,这⾥需要我们的注意。

DevexpressWinFormTreeList的三种数据绑定方式(DataSource。。。

DevexpressWinFormTreeList的三种数据绑定方式(DataSource。。。

DevexpressWinFormTreeList的三种数据绑定⽅式(DataSource。

第⼀种:DataSource绑定,这种绑定⽅式需要设置TreeList的ParentFieldName和KeyFieldName两个属性,这⾥需要注意的是KeyFieldName 的值必须是唯⼀的。

代码如下:private void Form1_Load(object sender, EventArgs e){try{//构建⼀个DataTable数据源DataTable table = new DataTable();table.Columns.Add("parentId");table.Columns.Add("Id");table.Columns.Add("parentName");table.Columns.Add("Name");DataRow row = table.NewRow();row["parentId"] = "";row["Id"] = "*";row["Name"] = "所有颜⾊";table.Rows.Add(row);row = table.NewRow();row["parentId"] = "*";row["Id"] = "1";row["Name"] = "红⾊";table.Rows.Add(row);row = table.NewRow();row["parentId"] = "*";row["Id"] = "2";row["Name"] = "黄⾊";table.Rows.Add(row);row = table.NewRow();row["parentId"] = "*";row["Id"] = "3";row["Name"] = "绿⾊";table.Rows.Add(row);row = table.NewRow();row["parentId"] = "1";row["Id"] = "01";row["Name"] = "粉红⾊";table.Rows.Add(row);row = table.NewRow();row["parentId"] = "2";row["Id"] = "02";row["Name"] = "鹅黄⾊";table.Rows.Add(row);treeList1.ParentFieldName = "parentId";treeList1.KeyFieldName = "Id";treeList1.DataSource = table;treeList1.ExpandAll();}catch (Exception ex){MessageBox.Show(ex.Message);}}private void treeList1_BeforeCheckNode(object sender, DevExpress.XtraTreeList.CheckNodeEventArgs e){e.State = (e.PrevState == CheckState.Checked ? CheckState.Unchecked : CheckState.Checked);}private void treeList1_AfterCheckNode(object sender, DevExpress.XtraTreeList.NodeEventArgs e){try{SetCheckedChildNodes(e.Node, e.Node.CheckState);SetCheckedParentNodes(e.Node, e.Node.CheckState);}catch (Exception ex){MessageBox.Show(ex.Message);}}///<summary>///设置⼦节点的状态///</summary>///<param name="node"></param>///<param name="check"></param>private void SetCheckedChildNodes(TreeListNode node, CheckState check){for (int i = 0; i < node.Nodes.Count; i++){node.Nodes[i].CheckState = check;SetCheckedChildNodes(node.Nodes[i], check);}}///<summary>///设置⽗节点的状态///</summary>///<param name="node"></param>///<param name="check"></param>private void SetCheckedParentNodes(TreeListNode node, CheckState check){if (node.ParentNode != null){bool b = false;CheckState state;for (int i = 0; i < node.ParentNode.Nodes.Count; i++){state = (CheckState)node.ParentNode.Nodes[i].CheckState;if (!check.Equals(state)){b = !b;break;}}node.ParentNode.CheckState = b ? CheckState.Checked : check;SetCheckedParentNodes(node.ParentNode, check);}}运⾏效果图:第⼆种:AppendNode添加节点代码如下:private void LoadTree(){//清空节点treeList1.BeginUnboundLoad();treeList1.ClearNodes();arrayList = new List<TreeListNode>();//绑定部位树树的第⼀层TreeListNode Node = treeList1.Nodes.Add(new object[] { "所有颜⾊", "*"});Node.Tag = "*";arrayList.Add(Node);//绑定第⼆层DataSet ds = SqlHelper.Query(@"select ctc.colorId as ParentNodeID,ctc.childcolorId as NodeID, s as NodeNamefrom C_colorTocolor ctc(nolock)inner join C_color cc(nolock) on ctc.childcolorId=cc.id");if (ds != null && ds.Tables.Count > 0){table = ds.Tables[0];DataRow[] rows = table.Select("ParentNodeID='*'");foreach (DataRow row in rows){TreeListNode tn = treeList1.AppendNode(new object[] { row["NodeName"].ToString(), row["NodeID"].ToString() }, Node.Id); tn.Tag = row["NodeID"].ToString();arrayList.Add(tn);BindNode(row["NodeID"].ToString(), tn);}}treeList1.EndUnboundLoad();treeList1.ExpandAll();}private void BindNode(string nodeId, TreeListNode tn){DataRow[] rows = table.Select("ParentNodeID='" + nodeId + "'");foreach (DataRow row in rows){TreeListNode tns = treeList1.AppendNode(new object[] { row["NodeName"].ToString(), row["NodeID"].ToString()}, tn.Id);tns.Tag = row["NodeID"].ToString();arrayList.Add(tns);BindNode(row["NodeID"].ToString(), tns);}}private void Form2_Load(object sender, EventArgs e){//绑定树LoadTree();}运⾏效果图:第三种:VirtualTreeGetChildNodes虚拟树加载。

WinForm中comboBox控件之数据绑定

WinForm中comboBox控件之数据绑定

WinForm中comboBox控件之数据绑定下⾯介绍三种对comboBox绑定的⽅式,分别是泛型中IList和Dictionary,还有数据集DataTable⼀、IList现在我们直接创建⼀个List集合,然后绑定View CodeIList<string> list = new List<string>();list.Add("111111");list.Add("222222");list.Add("333333");list.Add("444444");comboBox1.DataSource = list;执⾏后,我们会发现绑定成功,但是我们知道⼀般对于下拉框的绑定都会有⼀个值,⼀个显⽰的内容,这个时候我们可以创建⼀个类,把value和text都封装到这个类,作为list的类型public class Info{public string Id { get; set; }public string Name { get; set; }}private void bindCbox(){IList<Info> infoList = new List<Info>();Info info1 = new Info() { Id="1",Name="张三"};Info info2 = new Info() { Id="2",Name="李四"};Info info3 = new Info() { Id = "3",Name = "王五" };infoList.Add(info1);infoList.Add(info2);infoList.Add(info3);comboBox1.DataSource = infoList;comboBox1.ValueMember = "Id";comboBox1.DisplayMember = "Name";}这个时候我们就可以直接获得值和显⽰的内容了⼆、Dictionary这个有点特殊,不能直接绑定,需要借助类BindingSource才可以完成绑定View CodeDictionary<int, string> kvDictonary = new Dictionary<int, string>();kvDictonary.Add(1, "11111");kvDictonary.Add(2, "22222");kvDictonary.Add(3, "333333");BindingSource bs = new BindingSource();bs.DataSource = kvDictonary;comboBox1.DataSource = bs;comboBox1.ValueMember = "Key";comboBox1.DisplayMember = "Value";三、数据集这个⽐较常见,很简单View Code//数据集绑定private void BindCombox(){DataTable dt = new DataTable();DataColumn dc1 = new DataColumn("id");DataColumn dc2 = new DataColumn("name");dt.Columns.Add(dc1);dt.Columns.Add(dc2);DataRow dr1 = dt.NewRow();dr1["id"] = "1";dr1["name"] = "aaaaaa";DataRow dr2 = dt.NewRow();dr2["id"] = "2";dr2["name"] = "bbbbbb";dt.Rows.Add(dr1);dt.Rows.Add(dr2);comboBox1.DataSource = dt;comboBox1.ValueMember = "id";comboBox1.DisplayMember = "name";}注意:当我们触发combox的SelectedIndexChanged的事件后,我们在加载窗体的时候就会执⾏,这点我刚开始也和魅惑,导致容易出错,这点我们可以采取⼀些⽅法避免执⾏,⽐如可以定义⼀个变量fig=falseprivate void comboBox1_SelectedIndexChanged(object sender, EventArgs e){if(this.fig){string selectValue = this.cmbAddMember.SelectedValue.ToString();rtbaddMember.SelectedText = selectValue;}} 那么肯定想在加载窗体后,执⾏了,所以在加载窗体后我们还要把fig的值设为trueprivate void SetAutoMessage_Load(object sender, EventArgs e){loadCombox();loadMessageTemplet();fig= true;}。

C#WinForm_ComboBox数据绑定的问题

C#WinForm_ComboBox数据绑定的问题

Visual Studio C#中的数据绑定五.复杂型组件的数据绑定:在上面的介绍中,了解到对复杂型组件的数据绑定是通过设定组件的某些属性来完成数据绑定的。

首先来介绍一下ComboBox组件的数据绑定.(1).ComboBox组件的数据绑定:在得到数据集后,只有设定好ComboBox组件的的三个属性就可以完成数据绑定了,这三个属性是:、"DisplayMember"、"ValueMember"。

其中"DataSource"是要显示的数据集,"DisplayMember"是ComboBox 组件显示的字段,"ValueMember"是实际使用值。

具体如下:ComboBox1.DataSource = myDataSet ;ComboBox1.DisplayMember = "person.xm" ;ComboBox1.ValueMember = "person.xm" ;注释:此时绑定是Access 2000数据库中"person"表的"xm"字段。

由此可以得到ComboBox组件数据绑定的源程序代码(Combo01.cs),本代码操作数据库是Access 2000:public class Form1 : Form{private ComboBox ComboBox1 ;private Button button1 ;private System.Data.DataSet myDataSet ;private ponentModel.Container components = null ;public Form1 ( ){file://打开数据链接,得到数据集GetConnect ( ) ;InitializeComponent ( ) ;}file://清除程序中使用过的资源protected override void Dispose ( bool disposing ){if ( disposing ){if ( components != null ){components.Dispose ( ) ;}}base.Dispose ( disposing ) ;}private void GetConnect ( ){file://创建一个OleDbConnectionstring strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = db.mdb" ;OleDbConnection myConn = new OleDbConnection ( strCon ) ;string strCom = " SELECT * FROM person " ;file://创建一个DataSetmyDataSet = new DataSet ( ) ;myConn.Open ( ) ;file://用OleDbDataAdapter 得到一个数据集OleDbDataAdapter myCommand = new OleDbDataAdapter ( strCom , myConn ) ;file://把Dataset绑定person数据表myCommand.Fill ( myDataSet , "person" ) ;file://关闭此OleDbConnectionmyConn.Close ( ) ;}private void button1_Click ( object sender , System.EventArgs e ){ComboBox1.DataSource = myDataSet ;ComboBox1.DisplayMember = "person.xm" ;ComboBox1.ValueMember = "person.xm" ;}static void Main ( ){Application.Run ( new Form1 ( ) ) ;}}图03:对ComboBox组件数据绑定的程序界面得到了ComboBox组件对本地数据库的数据绑定程序,也就十分方便的得到ComboBox组件绑定Sql Server 2000源程序代码(Combox02.cs)具体如下:public class Form1 : Form{private ComboBox ComboBox1 ;private Button button1 ;private System.Data.DataSet myDataSet ;private ponentModel.Container components = null ;public Form1 ( ){file://打开数据链接,得到数据集GetConnect ( ) ;InitializeComponent ( ) ;}file://清除程序中使用过的资源protected override void Dispose ( bool disposing ){if ( disposing ){if ( components != null ){components.Dispose ( ) ;}}base.Dispose ( disposing ) ;}private void GetConnect ( ){// 设定数据连接字符串,此字符串的意思是打开Sql server数据库,服务器名称为server1,数据库为data1 string strCon = "Provider = SQLOLEDB.1 ; Persist Security Info = False ; User ID = sa ; Initial Catalog = data1 ; Data Source = server1 " ;OleDbConnection myConn = new OleDbConnection ( strCon ) ;myConn.Open ( ) ;string strCom = " SELECT * FROM person " ;file://创建一个DataSetmyDataSet = new DataSet ( ) ;file://用OleDbDataAdapter 得到一个数据集OleDbDataAdapter myCommand = new OleDbDataAdapter ( strCom , myConn ) ;file://把Dataset绑定person数据表myCommand.Fill ( myDataSet , " person " ) ;file://关闭此OleDbConnectionmyConn.Close ( ) ;}private void button1_Click ( object sender , System.EventArgs e ){ComboBox1.DataSource = myDataSet ;ComboBox1.DisplayMember = "person.xm" ;ComboBox1.ValueMember = "person.xm" ;}static void Main ( ){Application.Run ( new Form1 ( ) ) ;}}C# WinForm 中ComboBox数据绑定的问题2009-12-29 09:24怎样让WinForm中的ComboBox显示表中的一个字段,同时又绑定另一个字段?在Web中的ComboBox这样写可以绑定两个值:boBox1.DataTextField="B000602";//显示中文,方便用户选择boBox1.DataValueField="B000601";//绑定与选择对应的另一个值boBox1.DataBind();但是在WinForm程序中该怎么写啊?0******************************************************************DataSet ds = new DataSet();//这个DataSet是你从数据库里取出来的值string[] arr = new string[ds.Tables[0].Rows.Count];for (int i = 0; i < arr.Length; i++){arr[i] = ds.Tables[0].Rows[i][2].ToString();}textBox1.AutoCompleteCustomSource.AddRange(arr);textBox1.AutoCompleteSource =AutoCompleteSource.CustomSource;textBox1.AutoCompleteMode =AutoCompleteMode.SuggestAppend;1.******************************************************************* 假设combobox绑定的列表为DataSet2的ListTable表(含有ListID, ListName字段),需要绑定的记录字段为DataSet1的Table1表的ListID字段combobox.DataSource = dataset2.Tables["ListTable"]; combobox.DisplayMember = "ListName";combobox.ValueMember = "ListID";combobox.DataBindings.Add("SelectedValue", dataset1, "Table1.List ID");2.***************************************************************** //dt为数据表,ID,Name为dt的两个字段:comboBox1.DataSource = dt ;comboBox1.ValueMember ="ID";comboBox1.DisplayMember ="Name";3.******************************************************************SqlConnection con = new SqlConnection("server=192.168.2.198;uid=sa;pwd=sa;database=northwind"); SqlCommand cmd = con.CreateCommand();mandText = "Select * from Customers where countr y='USA'";SqlDataAdapter adp = new SqlDataAdapter();adp.SelectCommand = cmd;DataSet ds = new DataSet();adp.Fill(ds, "Customers");comboBox1.DataSource = ds.Tables["Customers"];comboBox1.DisplayMember = "CompanyName";comboBox1.ValueMember = "CompanyName";++++++++++++++++或者++++++++++++++++++++++SqlConnection con = new SqlConnection("server=192.168.2.198;uid=sa;pwd=sa;database=northwind"); SqlCommand cmd = con.CreateCommand();mandText = "Select * from Customers where countr y='USA'";SqlDataAdapter adp = new SqlDataAdapter();adp.SelectCommand = cmd;DataSet ds = new DataSet();adp.Fill(ds, "Customers");comboBox1.DataSource = ds;comboBox1.DisplayMember = "panyName";comboBox1.ValueMember = "panyName";++++++++++++往DataGrid里添加下拉列表++++++++++++ DataGridTableStyle dgt = new DataGridTableStyle();dgt.MappingName = "test";DataGridTextBoxColumn dgtbc = new DataGridTextBoxColumn(); dgtbc.MappingName = "name";dgtbc.HeaderText= "name";ComboBox cmbFunctionArea = new ComboBox(); cmbFunctionArea.DataSource = DtGeneral;cmbFunctionArea.DisplayMember = "name"; cmbFunctionArea.ValueMember = "value";cmbFunctionArea.Cursor = Cursors.Arrow;cmbFunctionArea.DropDownStyle= ComboBoxStyle.DropDownList;cmbFunctionArea.Dock = DockStyle.Fill;dgtbc.TextBox.Controls.Add(cmbFunctionArea);dgt.GridColumnStyles.Add(dgtbc);cmbFunctionArea.SelectionChangeCommitted +=new EventHandler(cmbFunctionArea_SelectionChangeCommitted);+++++++++++++修改++++++++++++++++private void cmbFunctionArea_SelectionChangeCommitted(object se nder, EventArgs e){((DataTable)dataGrid1.DataSource).Rows[dataGrid1.CurrentRowIndex][0] = ((ComboBox)sender).Text.ToString();dataGrid1.SetDataBinding(DtGeneral,null);}4.******************************************************************* *****DataBindings是一般控件所具有的,是绑定数据源的某一个字段combobox.DataBindings.Add("要绑定控件的属性如下拉框的SelectedValue\Text", 数据源如dataset1, "导航路径如Table1.ListID");但是,DataBindings只能绑定一个字段,而绑定多个字段时典型的如列表控件Combobox、ListBox控件,需要键值对,这时就需要指定DataSource(实现IList接口就行),然后指定ValueMember、DisplayMember 。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

WinForm数据绑定-简单绑定1数据绑定的意义在前面的文章中已经做了描述。

现在我们来具体了解一下数据绑定。

数据绑定被分为两个部分,(至少我是这样来分的)简单绑定和复杂绑定。

以一种简单的方式来理解的话,简单绑定是只控件和某个单一对象之间的绑定,而复杂绑定是指和集合(ArrayList, Array, DataTable, DataSet)之间的绑定,而复杂绑定中隐含着简单绑定。

所以我们必须先搞清楚简单绑定的想法(也是数据绑定实现的最基本的想法)。

前面描述过了数据绑定机制的想法是将数据和控件关联在一起的机制。

那对于一个单一对象而言什么是数据呢?对象本身其实就可能包含一定的数据。

比如我们知道的成员变量,它就在帮对象维持数据。

而对于数据绑定机制而言,它关心的是属性。

如果我们能将某个对象的属性和控件的某个属性关联在一起,那数据就可以自如的显示到控件中了。

所以对我的认识而言,我认为简单绑定做的事情就是将对象中的属性和控件的属性关联。

考虑一下的代码。

假设我定义了一个Person类,在这个类中我定义了三个属性FirstName, LastName, Age,我想将这三个属性分别显示在三个TextBox中。

如果不使用数据绑定我们需要的代码如下。

Person person = new Person("Cai", "Peng", 32);textbox1.Text = person.FirstName;textbox2.Text = stName;textBox3.Text = person.Age;这样做有什么问题吗?看来是没有什么问题,你的数据可以正常的显示在界面中。

问题就在与如果用户修改了textBox1中的数据,你的person对象中的FirstName的值也会更改吗?如果你想确保person.FirstName中的值和你的textBox1.Text的值一致的话你要怎么做?你必须编写相应的代码来完成。

比如你可以在textBox1的TextChanged事件中编写如下的代码:person.FirstName = textbox1.text这是不使用数据绑定时我们必须要做的事情。

在这样的情况下我们为了保证textBox1中的值和对象中相应的数据是一致,我们必须这样做。

如果使用数据绑定会怎么样呢?为了说明以上的这种转变,建立一个winform来说明一下:在这个项目中我建立了一个Person类和两个界面Form1, Form2.其中Form1不是用数据绑定。

person类:1using System;2using System.Collections.Generic; 3using System.Text;45namespace SimplyDataBinding6{7class Person8 {9private string _firstname;1011public string Firstname12 {13get { return _firstname; } 14set { _firstname = value; } 15 }16private string _lastname;1718public string Lastname19 {20get { return _lastname; }21set { _lastname = value; }22 }23private int _age;2425public int Age26 {27get { return _age; }28set { _age = value; }29 }30public Person() { }31public Person(string firstname, string lastname, int age) 32 {33this.Firstname = firstname;stname = lastname;35this.Age = age;36 }37 }38}39Form1.cs的界面:你可以尝试在第一行的第一个TextBox中键入一些内容,你会发现第二行的对应的TextBox中的值发生了改变。

但如果你去操作其他的TextBox就不会发现数据会发生相应的更改。

Form1的代码:1using System;2using System.Collections.Generic;34/*5 * 这个例子的想法是建立一个Person类的实例,然后将person的各个属性显示在相应的控件中。

6 * 界面中一共又6个TextBox,其中每三个Textbox用来显示person相应的三个属性。

7 * 你会发现如果在不使用数据绑定的情况下,显示数据是没有任何问题的。

8 * 但当你更改任意个Textbox中的数据的时候,你会发现相对应的另一个T extbox中的数据不会更新。

9 * 如果你想要是的两个显示相同person类同一属性的Textbox的数据保持一致,就需要编写相应的代码10 * 去处理。

我建立了第一个Textbox中的TextChanged事件,为了保证数据的一致。

1112 */13using ponentModel;14using System.Data;15using System.Drawing;16using System.Text;17using System.Windows.Forms;1819namespace SimplyDataBinding20{21public partial class Form1 : Form22 {23private Person person;24public Form1()25 {26 InitializeComponent();2728 person = new Person("Cai", "Peng", 32); 29this.txtFirstname1.Text = person.Firstname; 30this.txtLastname1.Text = stname; 31this.txtAge1.Text = person.Age.ToString(); 32this.txtFirstname2.Text = person.Firstname; 33this.txtLastname2.Text = stname; 34this.txtAge2.Text = person.Age.ToString();35 }3637private void button1_Click(object sender, EventArgs e)38 {3940 }4142private void txtFirstname1_TextChanged(object sender, EventArgs e) 43 {44//为了同步person.Firstname 和显示的数据。

我们必须写下如下的代码。

45 //你可以观察到其他的没有建立相应的TextChanged事件的Textbox 没又办法自动的46 //保证数据的一致。

47this.person.Firstname = this.txtFirstname1.Text;48this.txtFirstname2.Text = person.Firstname;49 }50 }51}代码中我建立了第一个控件的TextChanged事件,以便可以使得对应的两个Textbox的数据和person对象中的Firstname可以同步进行修改。

如果不使用数据绑定我们需要自己去编写代码处理上述的情况以及其他的更多的关于数据同步的情况。

下面我演示一下使用数据绑定的情况会如何Form2的界面和Form1的界面一致,你可以重复你在Form1中所做的事情,看看会怎么样。

注意一点,当你修改了控件中的数据后请将鼠标移动到其他的控件上去,以便数据绑定机制可以帮你做数据同步的事情。

Form2的代码:1using System;2using System.Collections.Generic;3using ponentModel;4using System.Data;5using System.Drawing;6using System.Text;7using System.Windows.Forms;89namespace SimplyDataBinding10{11public partial class Form2 : Form12 {13 Person person;14public Form2()15 {16 InitializeComponent();17 person = new Person("Cai", "Peng", 32);18this.txtFirstname1.DataBindings.Add("Text", person, "Firstname"); 19this.txtLastname1.DataBindings.Add("Text", person, "Lastname"); 20this.txtAge1.DataBindings.Add("Text", person, "Age");21this.txtFirstname2.DataBindings.Add("Text", person, "Firstname"); 22this.txtLastname2.DataBindings.Add("Text", person, "Lastname"); 23this.txtAge2.DataBindings.Add("Text", person, "Age");2425 }26 }27}你们应该可以发现这段代码和Form1中的代码的区别了吧。

以上的代码是以数据绑定的方式完成的。

后面我将详细解释这些代码。

你一定发现了,如果你做上述相同的操作的时候两个相应的TextBox始终会保持一致的数据。

而这一切的发生完全是自动的,这要得意于数据绑定了。

该解释一下了。

this.txtFirstname1.DataBindings.Add("Text", person, "Firstname");仔细看看,你能发现,"Text" 是不是就是TextBox的Text属性。

相关文档
最新文档