您的位置:首页 > 其它

Combobox 控件绑定数据

2015-10-12 20:02 393 查看
ComboBox 类:表示带有下拉列表的选择控件,通过单击控件上的箭头可显示或隐藏下拉列表。

绑定集合对象

// .xaml
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
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;
using System.Collections.ObjectModel;

namespace ComboboxDemo
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
// 集合实例化
User user = new User();
// 指定数据源
combobox.ItemsSource = user;
}
}

// 创建集合类
class User : ObservableCollection<string>
{
public User()
{
Add("张三");
Add("李四");
Add("王二");
Add("麻子");
}
}

}


// .cs
<Window x:Class="ComboboxDemo.MainWindow"                          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="ComboboxDemo" Height="182" Width="400">
<Grid Margin="0,0,0,-4" >
<ComboBox Name="combobox" Margin="0,20,0,101"/>
</Grid>
</Window>


结果:



绑定数据库

第一步:读取数据库中的数据到 DataSet 中,具体方法参照 ADO.NET 概述

string sql = String.Format("sql 语句");
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
ds.Clear();
da.Fill(ds);


第二步:指定数据源

combobox.ItemsSource = ds.Tables[0].DefaultView;
combobox.DisplayMemberPath = "数据表中列名称";
combobox.SelectedValuePath = "数据表中主键列名称";
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: