Question

I have a form (customersForm) displaying a datagridview with customer information. And a second form (viewForm) which allows the user to view, edit,delete and update selected datagridview row. When I click update, or delete i'd like the datagridview on the customerForm to refresh displaying the updated data. How can I do this from a button click?

This is the viewForms complete code:

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;



namespace Lewis_Warby_Airbrushing
{
    public partial class viewForm : Form
    {
        DataRowView Data = null;
        public viewForm(DataRowView dr)
        {
            InitializeComponent();
            Data = dr;
            }

        private void closeBTN_Click(object sender, EventArgs e)
        {

            this.Close();
        }

        private void viewForm_Load(object sender, EventArgs e)
        {
            refTxt.Text = Data["Reference"].ToString().Trim();
            firstTxt.Text = Data["First Name"].ToString().Trim();
            surenameTxt.Text = Data["Surename"].ToString().Trim();
            address1Txt.Text = Data["Address Line 1"].ToString().Trim();
            address2Txt.Text = Data["Address Line 2"].ToString().Trim();
            countyTxt.Text = Data["County"].ToString().Trim();
            postTxt.Text = Data["Post Code"].ToString().Trim();
            contactTxt.Text = Data["Contact Number"].ToString().Trim();
            emailTxt.Text = Data["Email Address"].ToString().Trim();



        }

        private void deleteBTN_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Customer information will be perminantly deteled. Do you with to continue? ", "Confirm Delete", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                string constring = @"Data Source=|DataDirectory|\LWADataBase.sdf";
                string Query = "delete from customersTBL where Reference ='" + this.refTxt.Text + "';";
                SqlCeConnection conDataBase = new SqlCeConnection(constring);
                SqlCeCommand cmdDataBase = new SqlCeCommand(Query, conDataBase);
                SqlCeDataReader myReader;
                try
                {
                    conDataBase.Open();
                    myReader = cmdDataBase.ExecuteReader();
                    MessageBox.Show("Customer information has been deleted", "Deleted Sucessfully");
                    while (myReader.Read())
                    {

                    }
                    MessageBox.Show("Please exit the Customers window and re-open to update the table");
                    this.Close();
                    //displays a system error message if a problem is found
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);

               }



            }

        }

        private void editBTN_Click(object sender, EventArgs e)

            {
                bool notEditable = true;
                if (editBTN.Text == "Update")
                {
                    int UserID = Convert.ToInt32(refTxt.Text);
                    UpdateDataBase( UserID );

                    editBTN.Text = "Edit";
                    deleteBTN.Visible = true;
                    notEditable = true;
                }
                else
                {
                    deleteBTN.Visible = false;
                    editBTN.Text = "Update";
                    deleteBTN.Visible = false;
                    notEditable = false;
                }
                firstTxt.ReadOnly = notEditable;
                surenameTxt.ReadOnly = notEditable;
                address1Txt.ReadOnly = notEditable;
                address2Txt.ReadOnly = notEditable;
                countyTxt.ReadOnly = notEditable;
                contactTxt.ReadOnly = notEditable;
                emailTxt.ReadOnly = notEditable;
                postTxt.ReadOnly = notEditable;

        }

private void UpdateDataBase(int customerID)
         {
             if (MessageBox.Show("Customer information will be updated. This change cannot be undone. Are you sure you want to continue? ", "Confirm Edit", MessageBoxButtons.YesNo) == DialogResult.Yes)
             {
                 string constring = @"Data Source=|DataDirectory|\LWADataBase.sdf";
                 string Query = @"update customersTBL set [First Name] = @fname,
                  surename = @sur, [Address Line 1] = @addr1,
                  [Address Line 2] = @addr2, County = @county,
                  [Post Code] = @pcode, [Email Address] = @mail, [Contact Number] = @ctNo
                  WHERE Reference = @id";
                 using (SqlCeConnection conDataBase = new SqlCeConnection(constring))
                 using (SqlCeCommand cmdDataBase = new SqlCeCommand(Query, conDataBase))
                 {
                     try
                     {
                         conDataBase.Open();
                         cmdDataBase.Parameters.AddWithValue("@fname", this.firstTxt.Text);
                         cmdDataBase.Parameters.AddWithValue("@sur", this.surenameTxt.Text);
                         cmdDataBase.Parameters.AddWithValue("@addr1", this.address1Txt.Text);
                         cmdDataBase.Parameters.AddWithValue("@addr2", this.address2Txt.Text);
                         cmdDataBase.Parameters.AddWithValue("@county", this.countyTxt.Text);
                         cmdDataBase.Parameters.AddWithValue("@pcode", this.postTxt.Text);
                         cmdDataBase.Parameters.AddWithValue("@mail", this.emailTxt.Text);
                         cmdDataBase.Parameters.AddWithValue("@ctNo", this.contactTxt.Text);
                         cmdDataBase.Parameters.AddWithValue("@id", customerID);
                         int rowsUpdated = cmdDataBase.ExecuteNonQuery();
                         if (rowsUpdated == 0)
                             MessageBox.Show("No customer found to update");
                         MessageBox.Show("Customer information sucessfully updated", "Update Sucessfull");
                     }
                     catch (Exception ex)
                     {
                         MessageBox.Show(ex.Message);
                     }
                 }
             }
}

The complete code for customerForm:

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;

namespace Lewis_Warby_Airbrushing
{
    public partial class customerForm : Form
    {
        public customerForm()
        {
            InitializeComponent();
        }




        public void customerForm_Load(object sender, EventArgs e)
        {

            // TODO: This line of code loads data into the 'lWADataBaseDataSet.customersTBL' table. You can move, or remove it, as needed.
            timer1.Start();
            this.lWADataBaseDataSet.EnforceConstraints = false;
            this.customersTBLTableAdapter.Fill(this.lWADataBaseDataSet.customersTBL);

        }

        private void viewBTN_Click(object sender, EventArgs e)
        {
            int selectedRowIndex = customersTBLDataGridView.SelectedCells[0].RowIndex;
            DataGridViewRow selectedRow = customersTBLDataGridView.Rows[selectedRowIndex];


            viewForm frm2 = new viewForm((DataRowView)selectedRow.DataBoundItem);
            frm2.ShowDialog();


        }
        addForm addForm = new addForm();
        private void addBTN_Click(object sender, EventArgs e)
        {
  if (addForm == null || addForm.IsDisposed == true)
                addForm = new addForm();
  addForm.ShowDialog();
  this.customersTBLTableAdapter.Fill(this.lWADataBaseDataSet.customersTBL);

        }

        int count = 0;
        private void timer1_Tick(object sender, EventArgs e)
        {
            count = customersTBLBindingSource.Count;
            statusLBL.Text = "You currently have "+count.ToString()+" customer(s) stored in this database";
        }
        searchForm searchForm = new searchForm();
        private void searchBTN_Click(object sender, EventArgs e)
        {
            if (searchForm == null || searchForm.IsDisposed == true);
            searchForm = new searchForm();
            searchForm.ShowDialog();
        }














        }


        }
Was it helpful?

Solution

There is a lot you don't specify in your question, but let's assume this scenario:

When customerView is shown, you call the database to fill a DataGridView with customer details. At some point you either dbl-click on a DGV row, or you select a row and click a button, and then show viewForm, passing in the data in the currently selected row. Again, you don't specify how this is done, but let's assume you pass in a Data Transfer Object of some kind.

Once done editing, you click a button, save the changes to the database, then close viewForm.

According to your comments this is the general workflow you have in your application now.

In this case, you can simply re-fetch the data, as you did when first showing customerView when the viewForm.ShowDialog() method returns.

Unless there is something else I don't get, this can be easily done like this:

//customerForm
private void button1_Click(object sender, EventArgs e)
{
        ViewFormClass viewForm = new ViewFormClass();
            viewForm.SetCustomerData(dataObject);
        viewForm.ShowDialog(); // will stop here waiting for viewForm to close
        this.FetchCustomerData();
}

where FetchCustomerData() is the same method you called when opening customerView. In there you would typically fetch the data and bind it to controls.

Cheers

EDIT:

As per your own code, with a simple modification:

        private void viewBTN_Click(object sender, EventArgs e)
        {
            int selectedRowIndex = customersTBLDataGridView.SelectedCells[0].RowIndex;
            DataGridViewRow selectedRow = customersTBLDataGridView.Rows[selectedRowIndex];


            viewForm frm2 = new viewForm((DataRowView)selectedRow.DataBoundItem);
            frm2.ShowDialog();
            this.customersTBLTableAdapter.Fill(this.lWADataBaseDataSet.customersTBL);


        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top