BindingSource的使用范例

来源:互联网 发布:菜谱录入软件 编辑:程序博客网 时间:2024/05/20 10:52

    public partial class Form1 : Form
    {

        private   DataSet gDataSet = GetDS();
        public Form1()
        {
            InitializeComponent();

    
            // Set the data source to the DataSet.
            bindingSource1.DataSource =gDataSet;

            //Set the DataMember to the Menu table.
            bindingSource1.DataMember = "Menu";

            // Add the control data bindings.
            neoDataGrid1.DataSource = bindingSource1;

            neoTextBox1.TxtBox.DataBindings.Add("Text", bindingSource1,
                "Beverages", true, DataSourceUpdateMode.OnPropertyChanged);
            neoTextBox2.DataBindings.Add("Text", bindingSource1,
                "Beverages", true, DataSourceUpdateMode.OnPropertyChanged);
            bindingSource1.BindingComplete +=
                new BindingCompleteEventHandler(bindingSource1_BindingComplete);

            textBox1.DataBindings.Add("Text", bindingSource1,
              "Beverages", true, DataSourceUpdateMode.OnPropertyChanged);
            textBox2.DataBindings.Add("Text", bindingSource1,
                "Beverages", true, DataSourceUpdateMode.OnPropertyChanged);
            bindingSource1.BindingComplete +=
                new BindingCompleteEventHandler(bindingSource1_BindingComplete);

        }


        public static DataSet GetDS()
        {
            DataSet set1 = new DataSet();
            set1.Tables.Add("Menu");
            set1.Tables[0].Columns.Add("Beverages");

            // Add some rows to the table.
            set1.Tables[0].Rows.Add("coffee");
            set1.Tables[0].Rows.Add("tea");
            set1.Tables[0].Rows.Add("hot chocolate");
            set1.Tables[0].Rows.Add("milk");
            set1.Tables[0].Rows.Add("orange juice");
            return set1;

        }

        public void AddNewRow()
        {
           

            DataRow newRow = (DataRow)bindingSource1.AddNew(); //新增一行数据
            newRow = ((DataRowView)this.bindingSource1.Current).Row; //取得新增的行
            //newRow.aUIDField = Guid.NewGuid();    //修改数据
            bindingSource1.ResetCurrentItem(); //刷新显示
        }

        private void bindingSource1_BindingComplete(object sender, BindingCompleteEventArgs e)
        {
            // Check if the data source has been updated, and that no error has occured.
            if (e.BindingCompleteContext ==
                BindingCompleteContext.DataSourceUpdate && e.Exception == null)

                // If not, end the current edit.
                e.Binding.BindingManagerBase.EndCurrentEdit();

        }

        private void neoButton1_Click(object sender, EventArgs e)
        {
            AddNewRow();
        }
    }

原创粉丝点击