当前位置:首页 > C#编程 > C#/.net框架 > 正文内容

c# listbox 实现datatable 绑定

秋天2年前 (2022-05-09)C#/.net框架776

 

如果你直接绑定DataTable表,如下面代码:

listBox1.DataSource = dt;

则会出现下图现象:

image.png


正确做法见代码:


C#
using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;
 namespace static绑定test{
    public partial class Form1 : Form    {
        public Form1()
        {
            InitializeComponent(); 
            dt.Columns.Add("age");
            dt.PrimaryKey = new DataColumn[] { dt.Columns[0] };
        }
        static List<string> list = new List<string>();
        DataTable dt = new DataTable();
        
        private void button1_Click(object sender, EventArgs e)
        {
           
            for (int i = 0; i < 10; i++)
            {
                dt.Rows.Add(i+"age");
            }
            listBox1.DataSource = dt ;
            // listBox1.DataBindings.Add("text",dt,"age");  经实验证明这句没有作用
            listBox1.DisplayMember = "age";  //要显示的字段,这句才是关键
        }
        private void button2_Click(object sender, EventArgs e)
        {
            dt.Rows.Add((dt.Rows.Count).ToString() + "age");
        }
 
        private void button3_Click(object sender, EventArgs e)
        {
            if (dt.Rows.Contains ("15age"))
            {
                MessageBox.Show("15");
            }
        }
    }}


结果正确!

image.png


那么问题来了,DataBindings是啥子东西?

请继续看:


TextBox控件的DataBindings属性

DataBindings属性是很多控件都有的属性,作用有2方面。一方面是用于与数据库的数据进行绑定,进行数据显示。另一方面用于与控件或类的对象进行数据绑定。这里主要关注后者。主要用法是将某个对象的某个属性与指定对象的指定属性进行关联.


Label、TextBox等都包含DataBindings属性,其类型为ControlBindingsCollection,是Binding类的集合。Binding类代表某对象属性值和某控件属性值之间的简单绑定。如可以将TextBox的Text属性值绑定到Label的Text属性值,这样,当TextBox中的文本被修改的时候,Label的文本也会及时进行修改,如下面的代码所示:


Label1.DataBindings.Add("Text",TextBox1,"Text");


Binding类除了可以将对象的属性绑定到控件的属性之外,还可以将对象列表中当前对象的属性值绑定到控件的属性。


当使用Binding的构造函数创建实例时,必须指定三项内容:


要绑定到的控件属性的名称

数据源

数据源中解析为列表或属性的导航路径

其中,数据源可以为:


实现 IBindingList 或 ITypedList 的任何类。包括:DataSet、DataTable、DataView 或 DataViewManager。 

实现 IList 的任意索引集合类。(必须在创建 Binding 之前创建和填充该集合,并且列表中的所有对象必须为同一类型,否则将引发异常) 

强类型对象的强类型 IList。

导航路径可以为空字符串(默认将调用数据源的ToString()方法)、单个属性名称或用点分隔的名称层次结构。


名称层次结构是什么意思呢?比如我们有一个Company类,它包含Name属性和Employees属性(公司所有Employee的集合),而Employee类又包含Name属性。那么,如果要将Company的Name属性绑定到TextBox控件的Text属性,代码为:


TextBox1.DataBindings.Add("Text", company, "Name");

如果要绑定Employees的Name属性,代码为:


TextBox1.DataBindings.Add("Text", company, "Employees.Name");

Employess.Name即为用点分隔的名称层次结构。在这里,Employees为一个集合,将Employees.Name绑定到TextBox会出现什么情况呢?测试后可知,TextBox将显示Employees集合中第一个Employee的Name属性。


示例:


界面

image.png

C#
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;namespace DataBindingsDemo{
    public partial class FrmDataBindings : Form    {
        public FrmDataBindings()
        {
            InitializeComponent();
        }

        private void FrmDataBindings_Load(object sender, EventArgs e)
        {
            //绑定到DataTable
            DataTable dtSource = GetDataTable();
            this.textBox1.DataBindings.Add("Text", dtSource, "StudentNo");
            this.textBox2.DataBindings.Add("Text", dtSource, "StudentName");
            this.textBox3.DataBindings.Add("Text", dtSource, "Sex");

            //绑定到实体对象
            Student stu = new Student() { StudentNo=2,StudentName="测试2",Sex="女"};
            //必须是绑定到对象的属性(此例中绑定到StudentNo,而不是student),
            this.textBox4.DataBindings.Add("Text", stu, "StudentNo");
            this.textBox5.DataBindings.Add("Text", stu, "StudentName");
            this.textBox6.DataBindings.Add("Text", stu, "Sex");
        }

        private DataTable GetDataTable()
        {
            DataTable dt = new DataTable();
            DataColumn dcNo = new DataColumn("StudentNo", typeof(Int32));
            DataColumn dcName = new DataColumn("StudentName", typeof(string));
            DataColumn dcSex = new DataColumn("Sex", typeof(string));
            dt.Columns.Add(dcNo);
            dt.Columns.Add(dcName);
            dt.Columns.Add(dcSex);
            dt.Rows.Add(new object[] { 1,"测试","男"});
            return dt;
        }
    }

    public class Student
    {
        private int studentNo;

        public int StudentNo        {
            get { return studentNo; }
            set { studentNo = value; }
        }

        private string studentName;

        public string StudentName        {
            get { return studentName; }
            set { studentName = value; }
        }

        private string sex;

        public string Sex        {
            get { return sex; }
            set { sex = value; }
        }
    }}

运行效果:


image.png


#转载请注明出处 www.skcircle.com 《少有人走的路》勇哥的工业自动化技术网站。

扫描二维码推送至手机访问。

版权声明:本文由7点博客发布,如需转载请注明出处。

本文链接:http://6dot.cn/?id=129

标签: .NET.NET框架
分享给朋友:

“c# listbox 实现datatable 绑定” 的相关文章

C# 控件闪烁问题的解决

C# 控件闪烁问题的解决

说一下解决C#下控件闪烁的几个问题,如下:  listview和datagridview显示数据闪烁 自定义控件的显示闪烁listbox滚动条拖动闪烁面板中控件过多的闪烁propertyGrid点击和修改项目缓慢的问题richtextbox控件的刷新显示问题此类问题对于界面复杂规...

C#的propertygrid控件,选择和修改项目时很慢

C#的propertygrid控件,选择和修改项目时很慢

C#的propertygrid控件是很强。可以实现类似Vitual Studio属性面板那样的效果。但是。。。。我们一直痛苦它在选择和修改项目的时候很慢。我的用法是使用控件的SelectObject来绑定数据。C# PgridMotionSpeed.SelectedObject ...

C#的变迁史 - C# 4.0 之线程安全集合篇

C#的变迁史 - C# 4.0 之线程安全集合篇

作为多线程和并行计算不得不考虑的问题就是临界资源的访问问题,解决临界资源的访问通常是加锁或者是使用信号量,这个大家应该很熟悉了。  而集合作为一种重要的临界资源,通用性更广,为了让大家更安全的使用它们,微软为我们带来了强大的并行集合:System.Collections.Concurrent里面的各...

C#字符串与享元(Flyweight)模式

C#字符串与享元(Flyweight)模式

注:关注这个话题是因为看到C#的关键字 lock时,其传入引用对象。因为string也是引用对象,所以能否做为lock的参数?对于这个问题,要搞明白C#的字符串的一个特点,它使用类似于享元模式的机制。因此在lock中锁字符串是相当不安全的。下面贴子是对C#字符串与享元模式的深入讨论。写这个文章,主要...

C#测量程序运行时间及cpu使用时间

C#测量程序运行时间及cpu使用时间

对一个服务器程序想统计每秒可以处理多少数据包,要如何做?答案是用处理数据包的总数,除以累记处理数据包用的时间。这里要指出的是, 运行一段程序,使用的cpu时间,跟实际运行的时间是不一样的。附例如下:C#private void ShowRunTime() {...

C#:多进程开发,控制进程数量

C#:多进程开发,控制进程数量

正在c#程序优化时,如果多线程效果不佳的情况下,也会使用多进程的方案,如下:C#System.Threading.Tasks.Task task=System.Threading.Tasks.Task.Factory.StartNew(     &...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。