WinForm之BindingSource基础操作实例教程

通常我们在进行数据绑定的时候,常用的数据源有DataSet、DataTable、BindingList<T>、还有强类型数据源。今天我们来通过实例了解一下BindingSource组建,分享给大家供大家参考借鉴之用。

BindingSource的两个用途:

(1)首先,它提供一个将窗体上的控件绑定到数据的间接层。这是通过将 BindingSource 组件绑定到数据源,然后将窗体上的控件绑定到 BindingSource 组件来完成的。与数据的所有进一步交互(包括导航、排序、筛选和更新)都是通过调用 BindingSource 组件来完成的。
(2)其次,BindingSource 组件可以充当强类型数据源。使用 Add 方法向 BindingSource 组件添加类型会创建一个该类型的列表。

一、对BindingSource的基础操作——增删改查

实例代码如下:

  public partial class Form1 : Form
  {
    //注当前DGV已经绑定到 ID 和 Name 列
    private BindingSource source = new BindingSource();
    public Form1()
    {
      InitializeComponent();
    }
    //窗体加载
    private void Form1_Load(object sender, EventArgs e)
    {
      this.source.DataSource = typeof(Custom);
      this.dataGridView1.DataSource = this.source;
    }
    //添加
    private void button1_Click(object sender, EventArgs e)
    {
      this.source.Add(new Custom(1,"A"));
      this.source.Add(new Custom(2,"B"));
    }
    //删除
    private void button2_Click(object sender, EventArgs e)
    {
      this.source.RemoveAt(0);
    }
    //排序 【有问题】
    private void button3_Click(object sender, EventArgs e)
    {
      this.source.Sort = "ID ASC";
      this.source.ResetBindings(false);
    }
    //筛选 【有问题】
    private void button4_Click(object sender, EventArgs e)
    {
      this.source.Filter = "ID = 1";
      this.source.ResetBindings(false);
    }
    //向下移动
    private void button5_Click(object sender, EventArgs e)
    {
      this.source.MoveNext();
      MessageBox.Show(this.source.Position.ToString());
    }
    //向上移动
    private void button9_Click(object sender, EventArgs e)
    {
      this.source.MovePrevious();
      MessageBox.Show(this.source.Position.ToString());
    }
    //获取当前项
    private void button6_Click(object sender, EventArgs e)
    {
      Custom custom = (Custom)this.source.Current;
      MessageBox.Show(" 所处的位置 : " + this.source.IndexOf(custom).ToString());
      MessageBox.Show("custom.Name : " + custom.Name);
    }
    //修改当前项
    private void button7_Click(object sender, EventArgs e)
    {
      Custom custom = (Custom)this.source.Current;
      custom.Name = "修改后的值";
      this.source.ResetCurrentItem();
    }
    //删除当前项
    private void button8_Click(object sender, EventArgs e)
    {
      Custom custom = (Custom)this.source.Current;
      this.source.Remove(custom);
    }
  }
  //自定义类 字段必须属性公开化
  public class Custom
  {
    public Custom()
    { }
    public Custom(int ID, string Name)
    {
      this.ID = ID;
      this.Name = Name;
    }
    private int id;
    public int ID
    {
      get { return id; }
      set { id = value; }
    }
    private string name;
    public string Name
    {
      get { return name; }
      set { name = value; }
    }
  }

二、  下面的示例演示如何在两种不同情况下绑定 DBNull 值。

第一种情况演示如何设置字符串属性的 NullValue;第二种情况演示如何设置图像属性的 NullValue。

下面的示例演示如何在两种不同情况下绑定 DBNull 值。第一种情况演示如何设置字符串属性的 NullValue;第二种情况演示如何设置图像属性的 NullValue。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace DBNullCS
{
  public class Form1 : Form
  {
    public Form1()
    {
      this.Load += new EventHandler(Form1_Load);
    }
    // The controls and components we need for the form.
    private Button button1;
    private PictureBox pictureBox1;
    private BindingSource bindingSource1;
    private TextBox textBox1;
    private TextBox textBox2;
    // Data table to hold the database data.
    DataTable employeeTable = new DataTable();
    void Form1_Load(object sender, EventArgs e)
    {
      // Basic form setup.
      this.pictureBox1 = new PictureBox();
      this.bindingSource1 = new BindingSource();
      this.textBox1 = new TextBox();
      this.textBox2 = new TextBox();
      this.button1 = new Button();
      this.pictureBox1.Location = new System.Drawing.Point(20, 20);
      this.pictureBox1.Size = new System.Drawing.Size(174, 179);
      this.textBox1.Location = new System.Drawing.Point(25, 215);
      this.textBox1.ReadOnly = true;
      this.textBox2.Location = new System.Drawing.Point(25, 241);
      this.textBox2.ReadOnly = true;
      this.button1.Location = new System.Drawing.Point(200, 103);
      this.button1.Text = "Move Next";
      this.button1.Click += new System.EventHandler(this.button1_Click);
      this.ClientSize = new System.Drawing.Size(292, 273);
      this.Controls.Add(this.button1);
      this.Controls.Add(this.textBox2);
      this.Controls.Add(this.textBox1);
      this.Controls.Add(this.pictureBox1);
      this.ResumeLayout(false);
      this.PerformLayout();
      // Create the connection string and populate the data table
      // with data.
      string connectionString = "Integrated Security=SSPI;" +
        "Persist Security Info = False;Initial Catalog=Northwind;" +
        "Data Source = localhost";
      SqlConnection connection = new SqlConnection();
      connection.ConnectionString = connectionString;
      SqlDataAdapter employeeAdapter =
        new SqlDataAdapter(new SqlCommand("Select * from Employees", connection));
      connection.Open();
      employeeAdapter.Fill(employeeTable);
      // Set the DataSource property of the BindingSource to the employee table.
      bindingSource1.DataSource = employeeTable;
      // Set up the binding to the ReportsTo column.
      Binding reportsToBinding = textBox2.DataBindings.Add("Text", bindingSource1,
        "ReportsTo", true);
      // Set the NullValue property for this binding.
      reportsToBinding.NullValue = "No Manager";
      // Set up the binding for the PictureBox using the Add method, setting
      // the null value in method call.
      pictureBox1.DataBindings.Add("Image", bindingSource1, "Photo", true,
        DataSourceUpdateMode.Never, new Bitmap(typeof(Button), "Button.bmp"));
      // Set up the remaining binding.
      textBox1.DataBindings.Add("Text", bindingSource1, "LastName", true);
    }
    // Move through the data when the button is clicked.
    private void button1_Click(object sender, EventArgs e)
    {
      bindingSource1.MoveNext();
    }
    [STAThread]
    static void Main()
    {
      Application.EnableVisualStyles();
      Application.Run(new Form1());
    }
  }
}

希望本文实例对大家C#程序设计的学习有所帮助!

(0)

相关推荐

  • C#实现WinForm捕获最小化事件的方法

    一般来说,虽然Form类没有提供Minimize的事件,但还是可以通过重载Deactive来实现WinForm捕获最小化事件. 实现方法为:当Form失去焦点后,测试WindowState取得Form状态,若为Minimized既是最小化事件. 本例为最小化后隐藏窗口: 还有种方法更加直接,重载WndProc: 实现代码如下: const int WM_SYSCOMMAND = 0x112; const int SC_CLOSE = 0xF060; const int SC_MINIMIZE =

  • WinForm中的几个实用技巧汇总

    本文汇总了几个WinForm中常见的实用技巧,对于C#程序开发有着很好的参考借鉴价值.具体分析如下: 一.屏蔽窗体右上角关闭按钮 1.重写OnClosing protected override void OnClosing(CancelEventArgs e) { if(this.Visible) { e.Cancel=true; // // WHATE TODO // } } 2.重写WndProc protected override void WndProc(ref Message m)

  • C#中Winform窗体Form的关闭按钮变灰色的方法

    本文实例讲述了C#中Winform窗体Form的关闭按钮变灰色的方法,对C#程序设计有一定的借鉴价值,分享给大家供大家参考之用.具体方法如下: 主要功能代码如下: [ DllImport ( "USER32.DLL" ) ] public static extern int GetSystemMenu(int hwnd, int bRevert); [ DllImport ( "USER32.DLL" ) ] public static extern int Rem

  • WinForm相对路径的陷阱

    本文所述为使用WinForm相对路径时需要注意的陷阱.这类错误经常会遇到!现分析如下供大家参考. 在Window系统上利用相对路径进行操作时,有一个"当前目录"的概念,如果程序中是利用相对路径进行操作,系统会认为是在当前目录下进行操作,即 相对路径 等于 当前目录 + 相对路径 所组成的绝对路径. 应用程序默认的当前目录为:程序入口所在路径. 并且在WinForm中,OpenFileDialog.RestoreDirectory 或 SaveFileDialog.SaveFileDia

  • Winform下实现图片切换特效的方法

    本文实例讲述了Winform下实现图片切换特效的方法,是应用程序开发中非常实用的一个功能.分享给大家供大家参考之用.具体方法如下: 本实例源自网络,功能较为齐全.丰富!主要功能代码如下: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Drawin

  • C#之WinForm WebBrowser实用技巧汇总

    本文实例汇总了C#中WinForm WebBrowser常见的实用技巧,对于C#程序开发来说有不错的借鉴价值.分别叙述如下: 方法1:获取状态栏信息 void webBrowser1_StatusTextChanged(object sender, EventArgs e) { label1.Text = webBrowser1.StatusText; } 方法2:页面跳转后改变地址栏地址 //在Navigated事件处理函数中改变地址栏地址是最恰当的: private void webBrow

  • WinForm中DefWndProc、WndProc与IMessageFilter的区别

    一般来说,Winform的消息处理机制多数时候是通过事件处理程序进行的,但当没有对应的事件时通常的做法是声明DefWndProc或者WndProc或者IMessageFilter,经常在网上看见有文章将三者并列,那么它们有什么区别呢?本文对此做一简单分析如下: DefWndProc和WndProc都是继承自Control类中的虚方法,其原型如下: protected override void DefWndProc(ref Message m) { .... base.DefWndProc(m)

  • c# 重载WndProc,实现重写“最小化”的实现方法

    code #1 复制代码 代码如下: private void Form1_SizeChanged(object sender, EventArgs e) //最小化隐藏窗体 { if (this.WindowState == FormWindowState.Minimized)//窗体状态为最小化 { StopRectTimer.Enabled = false; this.Visible = false; this.notifyIcon1.Visible = true; //显示系统托盘图标

  • C# Winform实现捕获窗体最小化、最大化、关闭按钮事件的方法

    本文实例讲述了C# Winform实现捕获窗体最小化.最大化.关闭按钮事件的方法,主要是通过重写WndProc来实现的.分享给大家供大家参考.具体方法如下: 主要功能代码如下: const int WM_SYSCOMMAND = 0x112; const int SC_CLOSE = 0xF060; const int SC_MINIMIZE = 0xF020; const int SC_MAXIMIZE = 0xF030; protected override void WndProc(ref

  • WinForm实现跨进程通信的方法

    本文实例展示了WinForm实现跨进程通信的方法,分享给大家供大家参考之用.具体方法如下: 主要功能代码如下: public class WinMessageHelper { private struct COPYDATASTRUCT { public IntPtr dwData; public int cbData; [MarshalAs(UnmanagedType.LPStr)] public string lpData; } //使用COPYDATA进行跨进程通信 public const

  • WinForm中变Enter键为Tab键实现焦点转移的方法

    本文实例讲述了WinForm中变Enter键为Tab键实现焦点转移的方法,在进行C#应用程序开发时有一定的实用价值.分享给大家供大家参考. 具体实现代码如下: /// <summary> /// 窗体控件控制相关的方法 /// </summary> public class ControlTools { private Form frm; public ControlTools(Form frm) { this.frm = frm; } /// <summary> //

随机推荐