【问题标题】:Unable to add Rows to DataGridView programically无法以编程方式将行添加到 DataGridView
【发布时间】:2019-02-25 17:05:27
【问题描述】:

我已经创建了一个采购订单表格并将所有数据添加到表格中。现在我想通过向DataGridView 添加新项目来更新采购订单项目。

我已经用旧项目填充DataGridView,现在我想添加新项目但它不起作用

错误:当控件是数据绑定时,行无法以编程方式添加到 DataGridView 行集合。

这是我用来在 updateMode 中添加新行的代码。

    try
            {
                if (updateMode)
                {
                    //DataTable dt = dataGridPOItems.DataSource as DataTable;
                    //DataRow rw = dt.NewRow();

                    //DataTable dt = dataGridPOItems.DataSource as DataTable;
                    //DataRow rw = dt.NewRow();

                    //var dataSource = dataGridPOItems.DataSource as BindingSource;
                    //var dataTable = dataSource.DataSource as DataTable;

                    DataTable dt = dataGridPOItems.DataSource as DataTable;
                    dt.Rows.Add();

                    dataGridPOItems.DataSource = dt;

                    int rowIndex = this.dataGridPOItems.RowCount;
                    var row = this.dataGridPOItems.Rows[rowIndex];

                    row.Cells["Product_ID"].Value = txtPOProdID.Text;
                    row.Cells["HSN"].Value = txtPOProdHSN.Text;
                    row.Cells["EAN"].Value = txtPOProdBarcode.Text;
                    row.Cells["PName"].Value = txtPOProdName.Text;
                    row.Cells["OrderQty"].Value = txtPOProdQtyReq.Text;
                    row.Cells["PMargin"].Value = txtPOProdMargin.Text;
                    row.Cells["MRP"].Value = txtPOProdMRP.Text;
                    row.Cells["GSTRate"].Value = txtPOProdGST.Text;

                    row.Cells["LandingCost"].Value = Math.Round(Convert.ToDecimal(row.Cells["MRP"].Value) - ((Convert.ToDecimal(row.Cells["MRP"].Value) * Convert.ToDecimal(row.Cells["PMargin"].Value) / 100)), 2);

                    row.Cells["BCost"].Value = Math.Round(Convert.ToDecimal(row.Cells["LandingCost"].Value) / (Convert.ToDecimal(row.Cells["GSTRate"].Value) / 100 + 1), 2);

                    row.Cells["BCostAmt"].Value = Convert.ToDecimal(row.Cells["BCost"].Value) * Convert.ToDecimal(row.Cells["OrderQty"].Value);

                    row.Cells["GSTAmt"].Value = Math.Round((Convert.ToDecimal(row.Cells["BCostAmt"].Value) * (Convert.ToDecimal(row.Cells["GSTRate"].Value) / 100)), 2);

                    row.Cells["NetAmt"].Value = Convert.ToDecimal(row.Cells["BCostAmt"].Value) + Convert.ToDecimal(row.Cells["GSTAmt"].Value);

                    txtPOProdQtyReq.Clear();

                    txtPOTotalItems.Text = Convert.ToString(rowIndex + 1);


                    foreach (DataGridViewColumn column in dataGridPOItems.Columns)
                    {
                        txtPOTotalQty.Text = dataGridPOItems.Rows.OfType<DataGridViewRow>().Sum(r => Convert.ToDecimal(r.Cells[4].Value)).ToString();
                        txtPOTCost.Text = dataGridPOItems.Rows.OfType<DataGridViewRow>().Sum(r => Convert.ToDecimal(r.Cells[12].Value)).ToString();
                        txtPOTAX.Text = dataGridPOItems.Rows.OfType<DataGridViewRow>().Sum(r => Convert.ToDecimal(r.Cells[10].Value)).ToString();

                    }

                    ClassControlsHandler.ClearAll(this.groupProdInfo);
                    txtPOProdID.Focus();


                }
                else
                {
                    int rowIndex = this.dataGridPOItems.Rows.Add();
                    var row = this.dataGridPOItems.Rows[rowIndex];

                    row.Cells["ProductID"].Value = txtPOProdID.Text;
                    row.Cells["HSN"].Value = txtPOProdHSN.Text;
                    row.Cells["EAN"].Value = txtPOProdBarcode.Text;
                    row.Cells["PName"].Value = txtPOProdName.Text;
                    row.Cells["OrderQty"].Value = txtPOProdQtyReq.Text;
                    row.Cells["PMargin"].Value = txtPOProdMargin.Text;
                    row.Cells["MRP"].Value = txtPOProdMRP.Text;
                    row.Cells["GSTRate"].Value = txtPOProdGST.Text;

                    row.Cells["LandingCost"].Value = Math.Round(Convert.ToDecimal(row.Cells["MRP"].Value) - ((Convert.ToDecimal(row.Cells["MRP"].Value) * Convert.ToDecimal(row.Cells["PMargin"].Value) / 100)), 2);

                    row.Cells["BCost"].Value = Math.Round(Convert.ToDecimal(row.Cells["LandingCost"].Value) / (Convert.ToDecimal(row.Cells["GSTRate"].Value) / 100 + 1), 2);


                    row.Cells["BCostAmt"].Value = Convert.ToDecimal(row.Cells["BCost"].Value) * Convert.ToDecimal(row.Cells["OrderQty"].Value);

                    row.Cells["GSTAmt"].Value = Math.Round((Convert.ToDecimal(row.Cells["BCostAmt"].Value) * (Convert.ToDecimal(row.Cells["GSTRate"].Value) / 100)), 2);

                    row.Cells["NetAmt"].Value = Convert.ToDecimal(row.Cells["BCostAmt"].Value) + Convert.ToDecimal(row.Cells["GSTAmt"].Value);

                    txtPOProdQtyReq.Clear();

                    txtPOTotalItems.Text = Convert.ToString(rowIndex + 1);


                    foreach (DataGridViewColumn column in dataGridPOItems.Columns)
                    {
                        txtPOTotalQty.Text = dataGridPOItems.Rows.OfType<DataGridViewRow>().Sum(r => Convert.ToDecimal(r.Cells[4].Value)).ToString();
                        txtPOTCost.Text = dataGridPOItems.Rows.OfType<DataGridViewRow>().Sum(r => Convert.ToDecimal(r.Cells[12].Value)).ToString();
                        txtPOTAX.Text = dataGridPOItems.Rows.OfType<DataGridViewRow>().Sum(r => Convert.ToDecimal(r.Cells[10].Value)).ToString();

                    }

                    ClassControlsHandler.ClearAll(this.groupProdInfo);
                    txtPOProdID.Focus();
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
            }

预期结果:我只想在 updateMode 中添加新行。

谢谢。

【问题讨论】:

  • 消息很清楚。相反,编辑并向 DataTable 添加行,网格将自动显示它们,因为它已连接到它。
  • 或者,将 DataTable 添加到 BindingSource.DatatSource 并使用 BindingSource 作为 DGV DataSource。它将允许直接从 DataGridView 向 DataTable 添加行(例如,将数据添加到 New Row(最后一行))。
  • @Jimi Sir,你能显示一些代码吗?

标签: c# winforms datagridview


【解决方案1】:

你可以这样试试吗?

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            dataGridView1.ColumnCount = 3;
            dataGridView1.Columns[0].Name = "Product ID";
            dataGridView1.Columns[1].Name = "Product Name";
            dataGridView1.Columns[2].Name = "Product Price";

            string[] row = new string[] { "1", "Product 1", "1000" };
            dataGridView1.Rows.Add(row);
            row = new string[] { "2", "Product 2", "2000" };
            dataGridView1.Rows.Add(row);
            row = new string[] { "3", "Product 3", "3000" };
            dataGridView1.Rows.Add(row);
            row = new string[] { "4", "Product 4", "4000" };
            dataGridView1.Rows.Add(row);
        }
    }
}

http://csharp.net-informations.com/datagridview/csharp-datagridview-add-column.htm

或者,简单地说。

private void InsertNewRowToDGV()
  {
   //we have to get the index of a last row id:
   int index = this.dataGridView1.Rows.Count;

   //and count +1 to get a new row id:
   index++;
   this.dataGridView1.Rows.Add();
}

【讨论】:

    【解决方案2】:

    这很简单:您可以使用BindingSource 并将DataTable 设置为BindingSource.DataSource,而不是直接使用DataTable

    BindingSource 将变为 DataGridView.DataSource

    private BindingSource dgvBindingSource = null;
    

    使用所需的Columns 创建DataTable 或使用DataAdapter 填充它,然后:

    DataTable dt = new DataTable("TableName");
    //Set the Columns or fill it with a DataAdapter
    
    dgvBindingSource = new BindingSource();
    dgvBindingSource.DataSource = dt;
    dataGridView1.DataSource = dgvBindingSource;
    dt.Dispose();
    

    当您需要在BindingSource 中添加新的DataRow 时,可以直接使用BindingSource.DataSource - 字段必须按正确的顺序提供:

    (dgvBindingSource.DataSource as DataTable).Rows.Add(new object[] {
        [Field1 Value], [Field2 Value], [Field3 Value], [Field N Value]
    });
    

    或添加一个新的DataRow 并使用Columns 名称分配字段值:

    using (DataTable dt = (dgvBindingSource.DataSource as DataTable))
    {
        DataRow row = dt.NewRow();
        row["Column0"] = SomeValue1;
        row["Column1"] = SomeValue2;
        row["Column2"] = SomeValue3;
        dt.Rows.Add(row);
    }
    

    这两种方法都会立即更新 DataGridView。

    【讨论】:

      猜你喜欢
      • 2014-09-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-11
      • 1970-01-01
      • 2014-10-16
      • 1970-01-01
      • 1970-01-01
      • 2020-10-15
      相关资源
      最近更新 更多