数据绑定(Data Binding)

来源:互联网 发布:colorpicker mac 编辑:程序博客网 时间:2024/05/16 08:03

数据绑定(Data Binding)

 

数据绑定是把一个值或一组值映射到用户界面控件的过程,这个数据并不一定是来自关系型数据库,通常是来自于程序之外的系统,访问数据,并把它转换复杂的绑定状态的过程还是相当简单的。这就是为什么我们在这一章,而不是在第八章讨论这个主题的原因。下面的例子演示把数据库中的表绑定到组合框:

 

open System

open System.Collections.Generic

open System.Configuration

open System.Data

open System.Data.SqlClient

open System.Windows.Forms

 

// creates a connections then executes thegiven command on it

let opener commandString =

  //read the connection string

  letconnectionSetting =

    ConfigurationManager.ConnectionStrings.["MyConnection"]

 

// create the connection and open it

let conn = newSqlConnection(connectionSetting.ConnectionString)

conn.Open()

 

// excute the command, ensuring the readwill close the connection

let cmd = conn.CreateCommand(CommandType =CommandType.Text,

                           CommandText =commandString)

cmd.ExecuteReader(CommandBehavior.CloseConnection)

 

// read each row from the data reader intoa dictionary

let generator (reader: IDataReader) =

  ifreader.Read() then

    letdict = new Dictionary<string, obj>()

    forx in [ 0 .. (reader.FieldCount - 1) ] do

     dict.Add(reader.GetName(x), reader.Item(x))

    Some(dict)

  else

    None

 

// executes a database command returning asequence containing the results

let execCommand commandString =

  Seq.generate

    (fun() -> opener commandString)

    (funr -> generator r)

    (funr -> r.Dispose())

 

// get the contents of the contacts table

let contactsTable =

  execCommand

    "selecttop 10 * from Person.Contact"

 

// create a list of first and last names

let contacts =

  [|for row in contactsTable ->

    Printf.sprintf"%O %O"

     (row.["FirstName"])

     (row.["LastName"]) |]

 

// create form containing a ComboBox withresults list

let form =

  lettemp = new Form()

  letcombo = new ComboBox(Top=8, Left=8, DataSource=contacts)

  temp.Controls.Add(combo)

  temp

 

// show the form

Application.Run(form)

 

运行前面的代码,可以看到如图 9-1 的结果。

图 9-1 数据绑定的组合框

 

我们把前面的例子拆开来看一下,首先执行这个查询:

 

let contactsTable =

  execCommand

    "select top 10 * fromPerson.Contact"

 

接着,把结果的可枚举集合转换成可绑定的组合框,首先需要获得重要成员,然后把它映射到字符串集合,最后再转换成数组。然后,把集合绑定到控件来显示,通过设置控件的 DataSource 属性,它是最后的命名参数:

 

let combo = new ComboBox(Top=8, Left=8,DataSource=contacts)

 

这一章的示例虽然只讨论了组合框,但是,大多数 Windows 和网站控件都可以用相似的方法进行绑定,包括列表框(ListBox)和选择列表框(CheckListBox)类。下一节,我们将学习把数据绑定到更复杂的控件,数据网格视图(DataGridView)类。

0 0