标题:TextBox数据绑定DataView出错,导致集合中的两个绑定绑定到同一个属性
只看楼主
niaomingjian
Rank: 1
等 级:新手上路
帖 子:10
专家分:0
注 册:2011-8-9
 问题点数:0 回复次数:0 
TextBox数据绑定DataView出错,导致集合中的两个绑定绑定到同一个属性
public partial class Form1 : Form
    {
        private DataView dv = new DataView();
        private BindingManagerBase bm;

        public Form1()
        {
            InitializeComponent();
            departmentNameTextBox1.ReadOnly = true;
            this.Load += new EventHandler(Form1_Load);

        }
        void Form1_Load(object sender, EventArgs e)
        {
            string sqlConnectString = @"Data Source=.\SQLEXPRESS;
                Integrated security=SSPI;Initial Catalog=AdventureWorks;";
            string sqlSelect = "SELECT * FROM HumanResources.Department";

            //使用Department表数据填充DataTable
            SqlDataAdapter da = new SqlDataAdapter(sqlSelect, sqlConnectString);
            DataTable dt = new DataTable();
            da.Fill(dt);

            // 基于表创建DataView,设置排序规则
            dv = dt.DefaultView;
            dv.Sort = "DepartmentID";

            // 创建数据绑定上下文
            bm = BindingContext[dv];

            // 为文本框2添加绑定
            departmentNameTextBox2.DataBindings.Add("Text", dv, "Name"); //编译时报错“这将导致集合中的两个绑定绑定到同一个属性”
            //完全按书上的例子写的,不知道哪里错了,自带源码运行无误,但自己写的一样的代码就是出错?
            //怎么会出现两个绑定绑定到同一个属性呢,这不只有一个绑定吗???????????????????????????
            // 初始化文本框
            departmentIDTextBox.Text = "1";
            GetDepartmentName(1);
        }

        private void GetDepartmentName(int departmentID)
        {
            // 在DataView中基于指定部门ID查找数据行
            int rowIndex = dv.Find(departmentID);
            if (rowIndex == -1)
            {
                MessageBox.Show("非法DepartmentID", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                departmentNameTextBox1.Text = (string)dv[rowIndex]["Name"];
                bm.Position = rowIndex;
            }
        }

        private void getNameButton_Click(object sender, EventArgs e)
        {
            int departmentID;

            // 提取信息
            if (int.TryParse(departmentIDTextBox.Text, out departmentID))
            {
                GetDepartmentName(departmentID);
            }
            else
            {
                MessageBox.Show("非法 DepartmentID", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
搜索更多相关主题的帖子: public private security 数据 class 
2012-02-25 15:37



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-361619-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.041658 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved