Winforms 绑定源问题添加新记录

Winforms bindingsource issue adding new record

我有以下代码将绑定数据加载到主从 window,其中主数据绑定到文本框和其他控件,详细数据绑定到 DataGridView:

在表单加载中:

    DataSet dsOrders = new DataSet("dsOrders");

            SqlDataAdapter daOrderHeader;// = new SqlDataAdapter();
            SqlDataAdapter daOrderDetail;// = new SqlDataAdapter();

            BindingSource bsOrderHeader = new BindingSource();
            BindingSource bsOrderDetail = new BindingSource();

    DataTable dtOrderHeader = new DataTable("dtOrderHeader");
                DataTable dtOrderDetail = new DataTable("dtOrderDetail");

                dsOrders.Tables.Add(dtOrderHeader);
                dsOrders.Tables.Add(dtOrderDetail);

                daOrderHeader = DataAdapterOrderHeader();
                daOrderDetail = DataAdapterOrderDetail();

                daOrderHeader.Fill(dtOrderHeader);
                daOrderDetail.Fill(dtOrderDetail);

                ////Set up a master-detail relationship between the DataTables
                DataColumn keyOrderHeaderColumn = dsOrders.Tables["dtOrderHeader"].Columns["ID"];
                DataColumn foreignKeyOrderDetailColumn = dsOrders.Tables["dtOrderDetail"].Columns["OrderId"];
                dsOrders.Relations.Add("rOrders", keyOrderHeaderColumn, foreignKeyOrderDetailColumn);

                bsOrderHeader.DataSource = dsOrders;
                bsOrderHeader.DataMember = "dtOrderHeader";
                bsOrderDetail.DataSource = bsOrderHeader;
                bsOrderDetail.DataMember = "rOrders";

tbxOrderNo.DataBindings.Add("Text", bsOrderHeader, "ID");
            tbxCustomer.DataBindings.Add("Text", bsOrderHeader, "Name");
            tbxTaxRate.DataBindings.Add("Text", bsOrderHeader, "TaxRate");
            tbxShipping.DataBindings.Add("Text", bsOrderHeader, "Shipping");
            tbxExchangeRate.DataBindings.Add("Text", bsOrderHeader, "ExchangeRate");
            dtpOrderDate.DataBindings.Add("Text", bsOrderHeader, "OrderDate");
            cbxPriceCode.DataBindings.Add("SelectedIndex", bsOrderHeader, "PriceCode");
            dgvItems.DataSource = bsOrderDetail;

enter code here

关于添加新记录:

DataRow drOrderHeader = dsOrders.Tables["dtOrderHeader"].NewRow();
            drOrderHeader["ID"] = (maxID + 1);
            dsOrders.Tables["dtOrderHeader"].Rows.Add(drOrderHeader);
            DataRow drOrderDetail = dsOrders.Tables["dtOrderDetail"].NewRow();
            drOrderDetail["OrderId"] = (maxID + 1);
            dsOrders.Tables["dtOrderDetail"].Rows.Add(drOrderDetail);
            bsOrderHeader.DataSource = dsOrders.Tables["dtOrderHeader"];
            bsOrderDetail.DataSource = dsOrders.Tables["dtOrderDetail"];

当我单击添加新行按钮时,bindingsource.count 属性 显示已添加新记录,但 winform 控件停留在同一记录上,我无法滚动到新创建的记录,也 bindingsource.movelast 停止工作。

有什么建议吗?我需要的是滚动到新添加的 record/row 并清除所有 winform 文本框并准备为新记录输入数据,除了我在创建时生成的 OrderId 和此代码中的 OrderId

更新:对“添加”按钮进行了更改,但未成功

newOrderId = Convert.ToInt32(dsOrders.Tables["dtOrderHeader"].Compute("max(ID)", string.Empty)) + 1;
            DataRow drOrderHeader = dsOrders.Tables["dtOrderHeader"].NewRow();
            drOrderHeader["ID"] = (newOrderId);
            dsOrders.Tables["dtOrderHeader"].Rows.Add(drOrderHeader);
            DataRow drOrderDetail = dsOrders.Tables["dtOrderDetail"].NewRow();
            drOrderDetail["OrderId"] = (newOrderId);
            dsOrders.Tables["dtOrderDetail"].Rows.Add(drOrderDetail);
            bsOrderHeader.Position = bsOrderHeader.Find("ID", newOrderId);

正如您已经发现的那样,数据绑定会检测您在基础数据源中所做的更改,因此有以下两行:

bsOrderHeader.DataSource = dsOrders.Tables["dtOrderHeader"];
bsOrderDetail.DataSource = dsOrders.Tables["dtOrderDetail"];

是多余的。不仅如此,第二个错误地更改了 bsOrderDetail 的数据源类型。所以简单地删除它们。

为了将UI重新绑定到新添加的记录,您只需将bsOrderHeaderPosition 属性设置为索引像这样的新记录:

bsOrderHeader.Position = bsOrderHeader.Find("ID", drOrderHeader["ID"]);

并且数据绑定基础结构将自动重新绑定主控件和(通过 DataRelation)详细信息网格视图。

编辑: 这是完整的工作演示。如果您的代码在更新后不起作用,那应该是由 post.

中未显示的其他代码部分引起的
using System;
using System.Data;
using System.Windows.Forms;

namespace Samples
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            var form = new Form();


            DataSet dsOrders = new DataSet("dsOrders");

            //SqlDataAdapter daOrderHeader;// = new SqlDataAdapter();
            //SqlDataAdapter daOrderDetail;// = new SqlDataAdapter();

            BindingSource bsOrderHeader = new BindingSource();
            BindingSource bsOrderDetail = new BindingSource();

            DataTable dtOrderHeader = new DataTable("dtOrderHeader");
            DataTable dtOrderDetail = new DataTable("dtOrderDetail");

            dsOrders.Tables.Add(dtOrderHeader);
            dsOrders.Tables.Add(dtOrderDetail);

            //daOrderHeader = DataAdapterOrderHeader();
            //daOrderDetail = DataAdapterOrderDetail();

            //daOrderHeader.Fill(dtOrderHeader);
            //daOrderDetail.Fill(dtOrderDetail);
            dtOrderHeader.Columns.Add("ID", typeof(int));
            dtOrderHeader.Columns.Add("Name", typeof(string));
            dtOrderHeader.Columns.Add("TaxRate", typeof(decimal));
            dtOrderHeader.Columns.Add("Shipping", typeof(string));
            dtOrderHeader.Columns.Add("ExchangeRate", typeof(decimal));
            dtOrderHeader.Columns.Add("OrderDate", typeof(DateTime));
            dtOrderHeader.Columns.Add("PriceCode", typeof(int));

            dtOrderHeader.PrimaryKey = new[] { dtOrderHeader.Columns["ID"] };

            dtOrderDetail.Columns.Add("OrderId", typeof(int));
            dtOrderDetail.Columns.Add("Quantity", typeof(decimal));

            ////Set up a master-detail relationship between the DataTables
            DataColumn keyOrderHeaderColumn = dsOrders.Tables["dtOrderHeader"].Columns["ID"];
            DataColumn foreignKeyOrderDetailColumn = dsOrders.Tables["dtOrderDetail"].Columns["OrderId"];
            var rel = dsOrders.Relations.Add("rOrders", keyOrderHeaderColumn, foreignKeyOrderDetailColumn);

            bsOrderHeader.DataSource = dsOrders;
            bsOrderHeader.DataMember = "dtOrderHeader";
            bsOrderDetail.DataSource = bsOrderHeader;
            bsOrderDetail.DataMember = "rOrders";

            var splitView = new SplitContainer { Dock = DockStyle.Fill, Parent = form };
            var tbxOrderNo = new TextBox();
            var tbxCustomer = new TextBox();
            var tbxTaxRate = new TextBox();
            var tbxShipping = new TextBox();
            var tbxExchangeRate = new TextBox();
            var dtpOrderDate = new DateTimePicker();
            int y = 8;
            foreach (var c in new Control[] { tbxOrderNo, tbxCustomer, tbxTaxRate, tbxShipping, tbxExchangeRate, dtpOrderDate })
            {
                c.Top = y;
                c.Left = 16;
                splitView.Panel1.Controls.Add(c);
                y = c.Bottom + 8;
            }

            var dgvItems = new DataGridView { Dock = DockStyle.Fill, Parent = splitView.Panel2 };

            tbxOrderNo.DataBindings.Add("Text", bsOrderHeader, "ID");
            tbxCustomer.DataBindings.Add("Text", bsOrderHeader, "Name");
            tbxTaxRate.DataBindings.Add("Text", bsOrderHeader, "TaxRate");
            tbxShipping.DataBindings.Add("Text", bsOrderHeader, "Shipping");
            tbxExchangeRate.DataBindings.Add("Text", bsOrderHeader, "ExchangeRate");
            dtpOrderDate.DataBindings.Add("Text", bsOrderHeader, "OrderDate");
            //cbxPriceCode.DataBindings.Add("SelectedIndex", bsOrderHeader, "PriceCode");
            dgvItems.DataSource = bsOrderDetail;


            Func<DataRow> addOrder = () =>
            {
                var maxOrderId = dsOrders.Tables["dtOrderHeader"].Compute("max(ID)", string.Empty);
                int newOrderId =  (maxOrderId != null && maxOrderId != DBNull.Value ? Convert.ToInt32(maxOrderId) : 0) + 1;
                DataRow drOrderHeader = dsOrders.Tables["dtOrderHeader"].NewRow();
                drOrderHeader["ID"] = newOrderId;
                dsOrders.Tables["dtOrderHeader"].Rows.Add(drOrderHeader);
                DataRow drOrderDetail = dsOrders.Tables["dtOrderDetail"].NewRow();
                drOrderDetail["OrderId"] = newOrderId;
                dsOrders.Tables["dtOrderDetail"].Rows.Add(drOrderDetail);
                return drOrderHeader;
            };

            for (int i = 0; i < 5; i++) addOrder();

            var addButton = new Button { Dock = DockStyle.Bottom, Parent = form, Text = "Add" };
            addButton.Click += (sender, e) =>
            {
                var drOrderHeader = addOrder();
                bsOrderHeader.Position = bsOrderHeader.Find("ID", drOrderHeader["ID"]);
            };

            Application.Run(form);
        }
    }
}