无法以编程方式将行添加到DataGridView

时间:2019-02-25 17:05:28

标签: c# winforms datagridview

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

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

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

enter image description here

这是我用来在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中添加新行。

谢谢。

2 个答案:

答案 0 :(得分:0)

您可以这样尝试吗?

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

答案 1 :(得分:0)

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

BindingSource将成为DataGridView.DataSource

private BindingSource dgvBindingSource = null;

使用所需的DataTable创建一个Columns或使用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。