Winforms绑定源问题添加新记录

时间:2016-04-12 05:53:53

标签: c# winforms datagridview dataset bindingsource

我有以下代码将绑定数据加载到master-detail窗口,其中主数据绑定到文本框以及绑定到DataGridView的其他控件和详细数据:

ON FORM LOAD:

    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 stoped working。 / p>

有什么建议吗?我需要的是滚动到新添加的记录/行,清除所有winform文本框并准备输入新记录的数据,除了我生成的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);

1 个答案:

答案 0 :(得分:0)

如您所见,数据绑定会检测您在基础数据源中所做的更改,因此会出现以下两行:

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

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

为了将UI重新绑定到新添加的记录,您只需要将bsOrderHeader的{​​{3}}属性设置为新记录的索引,如下所示:

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

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

编辑:这是完整的工作演示。如果您的代码在更新后不起作用,则应该由帖子中未显示的其他代码部分引起。

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);
        }
    }
}