-1

I have laboratory request window, i can create the new requests later on some times i need to update this order i made the update window and I read the order details from the database in datagrid view and i need to add new items to the datagridview, but the error when i add new row the existing rows removed and add the new row what is the error with my code and i am adding new row. How to add new row and keep existing rows, also check the attached files datagridview image before press enter key and datagridview1 image after press enter its add new row and remove the existing rows fetched from the database.

private void textAmount_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && textQty.Text != string.Empty && textAmount.Text != string.Empty)
            {
                if (chkcash1.Checked == true)
                {
                    textDiscount.Focus();
                }
                if (chkcash1.Checked == false)
                {
                    for (int i = 0; i < TestsDataGrid.Rows.Count - 1; i++)
                    {
                        if (TestsDataGrid.Rows[i].Cells[0].Value.ToString() == textTestId.Text)
                        {
                            MessageBox.Show("This test added already ", "Duplicate Test", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            return;
                        }
                    }
                    DataRow r = dt.NewRow();
                    r[0] = textTestId.Text;
                    r[1] = textName.Text;
                    r[2] = textPrice.Text;
                    r[3] = textQty.Text;
                    r[4] = textAmount.Text;
                    r[5] = textTotal.Text;


                    dt.Rows.Add(r);
                    TestsDataGrid.DataSource = dt;
                    textTestId.Clear();
                    textName.Clear();
                    textPrice.Clear();
                    textAmount.Clear();
                    textTotal.Clear();
                    btnSearch.Focus();

                    textOrderTotal.Text = (from DataGridViewRow row in TestsDataGrid.Rows
                                           where row.Cells[4].FormattedValue.ToString() != string.Empty
                                           select Convert.ToDouble(row.Cells[4].FormattedValue)).Sum().ToString();
                }[datagridviewimage][1]
  • 1
    Punctuation is your friend. – Fang Dec 26 '17 at 05:37
  • Yeah, i didn't make it past the 3rd line – TheGeneral Dec 26 '17 at 05:47
  • I even had this in word to edit it, and i'm still confused. Please step away from the coffee! – TheGeneral Dec 26 '17 at 05:51
  • How many rows dt has before adding new row? and dt is the source that you used as a datasource for datagrid? – maddy23285 Dec 26 '17 at 05:55
  • 1
    @Saruman sorry for my weak english i am not fluent in english I will try to order the question –  Dec 26 '17 at 05:59
  • @maddy first step I select the order which i need to update and i fill datagridview with order details from this stored procedure –  Dec 26 '17 at 06:29
  • TestsDataGrid.DataSource = dt; will clear all existing rows from datagrid and show only those data which exists in dt. So, if your dt has only one row it will show only one row in your datagrid. So, first you need to convert data of your datagrid to datatable. After that any changes in datatable will reflect in datagrid. – maddy23285 Dec 26 '17 at 06:34
  • @maddy first step I select the order which i need to update and i fill datagridview with order details from the stored procedure. In my case the datagrid view can include 4 rows or more rows fetched from database, then I add new row to dt. how can i keep the fetched rows and add new row to dt. ? –  Dec 26 '17 at 06:35
  • @maddy how to convert data in datagrid to datatable can you give me example? –  Dec 26 '17 at 06:44
  • @ziadqasem: check this link for conversion or else you can use a better approach in quick example below https://stackoverflow.com/questions/3109009/how-to-make-a-datatable-from-datagridview-without-any-datasource – maddy23285 Dec 26 '17 at 07:21

2 Answers2

1

This might help, here is a quick example:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlServerCe;
using System.Data.OleDb;

namespace Practice
{
    public partial class Form1 : Form
    {
        private DataTable retdt;
        SqlCeDataAdapter da;
        SqlCeCommandBuilder cbuild;
        SqlCeConnection con;
        public Form1()
        {
            InitializeComponent();
            fetchData();
        }
        private void fetchData()
        {
            retdt = new DataTable();
            SqlCeConnection con = null;
            try
            {
                con = new SqlCeConnection(@"Data Source=c:\users\mswami\documents\visual studio 2010\Projects\Practice\Practice\practice.sdf");
                da = new SqlCeDataAdapter();
                da.SelectCommand = new SqlCeCommand("select uid,amount from TestTable", con);
                cbuild = new SqlCeCommandBuilder(da);
                con.Open();
                da.Fill(retdt);
                DGPractice.DataSource = retdt.DefaultView;
                DGPractice.BindingContext = this.BindingContext;
            }
            catch (Exception exce)
            {
                MessageBox.Show(exce.Message);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (maskedTextBox1.Text.Length > 0)
            {
                if (retdt.Select("amount=" + maskedTextBox1.Text).Length == 0)
                {
                    DataRow drow = retdt.NewRow();
                    // drow[0] left blank as it is primary key column with auto increment value
                    drow[1] = Math.Round(Double.Parse(maskedTextBox1.Text),2);
                    retdt.Rows.Add(drow);

                    //Update changes into database table
                    // First process deletes.  
                    da.Update(retdt.Select(null, null, DataViewRowState.Deleted));

                    // Next process updates.  
                    da.Update(retdt.Select(null, null,
                      DataViewRowState.ModifiedCurrent));

                    // Finally, process inserts.  
                    da.Update(retdt.Select(null, null, DataViewRowState.Added));

                    DGPractice.DataSource = null;
                    DGPractice.DataSource = retdt.DefaultView;
                    DGPractice.BindingContext = this.BindingContext;
                }
                else
                {
                    MessageBox.Show("Duplicate amount");
                }
            }
        }
    }

}

Preview

designer.cs Code (For DataGrid column definition and binding properties)

 // DGPractice
// 
this.DGPractice.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.DGPractice.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.UID,
this.amtField});
this.DGPractice.Location = new System.Drawing.Point(2, 63);
this.DGPractice.Name = "DGPractice";
this.DGPractice.RowHeadersVisible = false;
this.DGPractice.Size = new System.Drawing.Size(373, 196);
this.DGPractice.TabIndex = 0;
// 
// UID
// 
this.UID.DataPropertyName = "uid";
this.UID.HeaderText = "UID";
this.UID.Name = "UID";
// 
// amtField
// 
this.amtField.DataPropertyName = "amount";
this.amtField.HeaderText = "Amount";
this.amtField.Name = "amtField";

DataPropertyName should be same as field name as in select query (table field name).

maddy23285
  • 738
  • 6
  • 16
0

thank you Maddy its solved my error its not keeping the data in datagrid view because i read from stored procedure and didnt save the data after fetch into datatable

da.Fill(retdt);
DGPractice.DataSource = retdt.DefaultView;
DGPractice.BindingContext = this.BindingContext;