Невозможно добавить строки в DataGridView программно - PullRequest
0 голосов
/ 25 февраля 2019

Я создал форму заказа на покупку и добавил все данные в таблицы.теперь я хотел обновить элементы заказа на покупку, добавив новые элементы в 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 голосов
/ 13 марта 2019

Это довольно просто: вместо прямого использования DataTable в качестве DataGridView.DataSource вы можете использовать BindingSource и установить DataTable в качестве 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();

Когда вам нужно добавить новый DataRow к BindingSource, вы можете использовать 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.

0 голосов
/ 11 марта 2019

Можете ли вы попробовать это так?

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();
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...