none
C# WPF查询数据库中的两个栏位,分别绑定到两个ComboBox,请问该如何操作? RRS feed

  • 问题

  • 查询的数据为同一个表中的两个栏位,一个是权限代码,一个是权限描述。

    将权限代码和权限描述分别绑定到ComboBox中,选择代码会自动选择对应的描述,反之亦然。(这一步已经向大神咨询过)

    现在面临的问题是,如何将查询出来的数据,绑定到各自的ComboBox中。

    请大神赐教哟。

    2014年6月9日 0:57

答案

  • 你好。

    很高兴帮你解决了两个ComboBox关联选择的问题,接下来数据绑定的问题,可以这样解决。

    我们从数据库或其他源读取数据后,会填充到我们定义的类里面。

    我们假设权限(Competence)是一个类,包括了权限代码(Code),权限描述等属性(Description)。那么可以把这两个ComboBox的ItemsSource都设置为Competence泛型的列表,然后分别设置它们的DisplayMemberPath为Code和Description。

    这里是简单的代码:

    XAML:

    <ComboBox Name="itemsNumber" Width="200" Height="30" DisplayMemberPath="Code" SelectedIndex="{Binding ElementName=items, Path=SelectedIndex, Mode=OneWay}"/>
    <ComboBox Name="items" Width="200" Height="30" DisplayMemberPath="Description" SelectedIndex="{Binding ElementName=itemsNumber, Path=SelectedIndex, Mode=OneWay}"/>

    C#:

    List<Competence> dataList = new List<Competence>();
    dataList.Add(new Competence() { Code = "001", Description = "Description of 001" });
    dataList.Add(new Competence() { Code = "002", Description = "Description of 002" });
    dataList.Add(new Competence() { Code = "003", Description = "Description of 003" });
    
    items.ItemsSource = dataList;
    itemsNumber.ItemsSource = dataList;

    以下是Competence类的定义:

    public class Competence
    {
        public string Code { get; set; }
        public string Description { get; set; }
    }
    希望对你有帮助!


    2014年6月9日 1:13
  • 看着范例的写法是调用GetAuthorityCodes返回一条数据,你可以稍作修改让它满足你的需求。

    按钮点击事件中去调用db类中的GetAuthorityCodes方法,但是返回值不要用Authority,而是用List<Authority>。

    然后就可以利用返回的List<Authority>类型的数据源来绑定ComboBox了。

    GetAuthorityCodes方法修改如下:

    public List<Authority> GetAuthorityCodes() { SqlConnection conn = new SqlConnection(connString); SqlCommand cmd = new SqlCommand("select * from authority", conn); cmd.CommandType = CommandType.Text; List<Authority> authorityList = new List<Authority>(); try { conn.Open(); SqlDataReader rd = cmd.ExecuteReader(CommandBehavior.Default); while (rd.Read()) { Authority authority = new Authority((string)rd["Authority"], (string)rd["Description"]); authorityList.Add(authority); }

    rd.Close(); } finally { conn.Close(); }

    return authorityList; }

    另外关于DataReader的使用,参考:使用 DataReader 检索数据



    2014年6月9日 4:33

全部回复

  • 你好。

    很高兴帮你解决了两个ComboBox关联选择的问题,接下来数据绑定的问题,可以这样解决。

    我们从数据库或其他源读取数据后,会填充到我们定义的类里面。

    我们假设权限(Competence)是一个类,包括了权限代码(Code),权限描述等属性(Description)。那么可以把这两个ComboBox的ItemsSource都设置为Competence泛型的列表,然后分别设置它们的DisplayMemberPath为Code和Description。

    这里是简单的代码:

    XAML:

    <ComboBox Name="itemsNumber" Width="200" Height="30" DisplayMemberPath="Code" SelectedIndex="{Binding ElementName=items, Path=SelectedIndex, Mode=OneWay}"/>
    <ComboBox Name="items" Width="200" Height="30" DisplayMemberPath="Description" SelectedIndex="{Binding ElementName=itemsNumber, Path=SelectedIndex, Mode=OneWay}"/>

    C#:

    List<Competence> dataList = new List<Competence>();
    dataList.Add(new Competence() { Code = "001", Description = "Description of 001" });
    dataList.Add(new Competence() { Code = "002", Description = "Description of 002" });
    dataList.Add(new Competence() { Code = "003", Description = "Description of 003" });
    
    items.ItemsSource = dataList;
    itemsNumber.ItemsSource = dataList;

    以下是Competence类的定义:

    public class Competence
    {
        public string Code { get; set; }
        public string Description { get; set; }
    }
    希望对你有帮助!


    2014年6月9日 1:13
  • Hi,大神。

    权限代码有好多,能不能直接从数据库里面查出来,然后绑定上去啊。

    :)

    2014年6月9日 1:42
  • 可以的。

    你可以选择一次性查询代码和描述做绑定,指定DisplayMemberPath。也可以分别查询代码和描述,分别去绑定。

    2014年6月9日 2:07
  • 比如说我用select code, description from authority查到的结果,

    我不知道怎么能将他们分别绑定到权限代码和权限描述的ComboBox里面去。

    dataTable和defaultView那一部分,始终没有理清楚。

    :(

    2014年6月9日 2:12
  • 这样的话,你需要从dataTable把数据填充到你定义的Competence类的集合里。大概过程是这样的:

    List<Competence> competences = new List<Competence>();
    for (int i = 0; i < dataTable.Rows.Count; i++)
    {
        competences.Add(new Competence()
                        {
                            Code=dataTable.Rows[i]["code"].ToString(),
                            Description=dataTable.Rows[i]["description"].ToString(),
                        });
    }
    

    这样就得到了一个Competence的列表,接下来就可以把这个列表绑定到ComboBox了。

    • 已建议为答案 shao.meng 2014年6月9日 4:33
    2014年6月9日 2:22
  • 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.Data;
    using System.Data.SqlClient;
    
    namespace Authority
    {
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
    
                listboxCodes.SelectedIndex = 0;
            }
    
            public class db //数据库连接类
            {
                private string connString = "server=localhost;uid=username;pwd=password;database=TEST_DB";
    
                public Authority GetAuthorityCodes() //这一行是什么意思呢?
                {
                    SqlConnection conn = new SqlConnection(connString);
                    SqlCommand cmd = new SqlCommand("select * from authority", conn);
                    cmd.CommandType = CommandType.Text;
    
                    try
                    {
                        conn.Open();
                        SqlDataReader rd = cmd.ExecuteReader(CommandBehavior.SingleRow); //这一行是什么意思呢?
                        if (rd.Read())
                        {
                            Authority authority = new Authority((string)rd["Authority"], (string)rd["Description"]);
                            return (authority);
                        }
    
                        else
                        {
                            return null;
                        }
    
                    }
    
                    finally
                    {
                        conn.Close();
                    }
                }
            }
    
            public class Authority
            {
                private string code;
                public string Code
                {
                    get { return code; }
                    set { code = value; }
                }
    
                private string description;
                public string Description
                {
                    get { return description; }
                    set { description = value; }
                }
    
                public Authority(string code, string description)
                {
                    Code = code;
                    Description = description;
                }
            }
    
            private void buttonGetCodes_Click(object sender, RoutedEventArgs e)
            {
                //这里该怎么写呢,我预想的功能是,点击这个按钮之后,把数据库里面所有的权限代码,显示在listboxCodes中去
            }
        }
    }
    

    大神,我在网上找了模块范例,跟着做了一下,帮我看看呗。

    按钮点击之后,不知道该怎么写了。

    2014年6月9日 3:55
  • 看着范例的写法是调用GetAuthorityCodes返回一条数据,你可以稍作修改让它满足你的需求。

    按钮点击事件中去调用db类中的GetAuthorityCodes方法,但是返回值不要用Authority,而是用List<Authority>。

    然后就可以利用返回的List<Authority>类型的数据源来绑定ComboBox了。

    GetAuthorityCodes方法修改如下:

    public List<Authority> GetAuthorityCodes() { SqlConnection conn = new SqlConnection(connString); SqlCommand cmd = new SqlCommand("select * from authority", conn); cmd.CommandType = CommandType.Text; List<Authority> authorityList = new List<Authority>(); try { conn.Open(); SqlDataReader rd = cmd.ExecuteReader(CommandBehavior.Default); while (rd.Read()) { Authority authority = new Authority((string)rd["Authority"], (string)rd["Description"]); authorityList.Add(authority); }

    rd.Close(); } finally { conn.Close(); }

    return authorityList; }

    另外关于DataReader的使用,参考:使用 DataReader 检索数据



    2014年6月9日 4:33
  • Hi

    多谢指导,终于做成功了啊~~谢谢您了

    不过,其实现在还有一个小BUG,

    左边选择之后,右边会自动变化,不过再选择右边的,左边不会自动变化。

    --前台
    <ComboBox Name="listboxCodes" DisplayMemberPath="Code" Height="30" SelectedIndex="{Binding ElementName=listboxDescription, Path=SelectedIndex,Mode=OneWay}" HorizontalAlignment="Left"  Margin="35,49,0,0" VerticalAlignment="Top" Width="186"/>
            <ComboBox Name="listboxDescription" DisplayMemberPath="Description" Height="30" SelectedIndex="{Binding ElementName=listboxCodes, Path=SelectedIndex,Mode=OneWay}" HorizontalAlignment="Left"  Margin="258,49,0,0" VerticalAlignment="Top" Width="186"/>
    
    --后台
    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.Data;
    using System.Data.SqlClient;
    
    namespace Authority
    {
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
    
                listboxCodes.SelectedIndex = 0;
            }
    
            public class db //数据库连接类
            {
                private string connString = "server=109.100.10.31;uid=zhangjie;pwd=zj2013;database=TEST_HDIDB_TEST";
    
                public List<Authority> GetAuthorityCodes() //这一行是什么意思呢?
                {
                    SqlConnection conn = new SqlConnection(connString);
                    SqlCommand cmd = new SqlCommand("select * from authority", conn);
                    cmd.CommandType = CommandType.Text;
                    List<Authority> authorityList = new List<Authority>();
    
                    try
                    {
                        conn.Open();
                        SqlDataReader rd = cmd.ExecuteReader(CommandBehavior.Default); //这一行是什么意思呢?
                        while (rd.Read())
                        {
                            Authority authority = new Authority((string)rd["Authority"], (string)rd["Description"]);
                            authorityList.Add(authority);
                        }
    
                        rd.Close();
                    }
    
                    finally
                    {
                        conn.Close();
                    }
    
                    return authorityList;
                }
            }
    
            public class Authority
            {
                private string code;
                public string Code
                {
                    get { return code; }
                    set { code = value; }
                }
    
                private string description;
                public string Description
                {
                    get { return description; }
                    set { description = value; }
                }
    
                public Authority(string code, string description)
                {
                    Code = code;
                    Description = description;
                }
            }
    
            private void buttonGetCodes_Click(object sender, RoutedEventArgs e)
            {
                db dbcodes = new db();
                listboxCodes.ItemsSource = listboxDescription.ItemsSource = dbcodes.GetAuthorityCodes();
            }
        }
    }
    

    2014年6月9日 5:37
  • 左右两侧的ComboBox都要做 SelectedIndex="{Binding ElementName=另一个ComboBox的name, Path=SelectedIndex, Mode=OneWay}"。这样就可以双向选择了。
    2014年6月9日 5:59
  • 我就是那么做的,又重新用智能感应写了一次Binding部分的代码,也还是不行呢。
    2014年6月9日 7:08
  • 我做了一个这样的尝试:

    第一个mode使用Oneway

    第二个mode使用twoway

    竟然达到目的了。好奇怪。

    之前我都是用你说的,两个都是oneway的,之前没有绑定哪些数据,就是用自己写的。

    绑定数据库数据之后,就不行了,要改成twoway。

    ---

    2014年6月9日 7:14