16

After entering data into all the textbox, and after clicking the submit button, it won't immediately show in the datagridview, I need to reopen the form in order to see the new inserted row. What code to put in for refresh?

Followed @user3222297 code. by adding grdPatient.Update(); and grdPatient.Refresh(); still doesn't get refreshed after i click the OK for insert successful.

doesn't get refresh

     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.SqlClient;
using System.Configuration;

namespace GRP_02_03_SACP
{
    public partial class patient : Form
    {
        // Data Table to store employee data
        DataTable Patient = new DataTable();

        // Keeps track of which row in Gridview
        // is selected
        DataGridViewRow currentRow = null;

        SqlDataAdapter PatientAdapter;

        public patient()
        {
            InitializeComponent();
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            if (btnSubmit.Text == "Clear")
            {
                btnSubmit.Text = "Submit";

                txtpFirstName.Focus();
            }
            else
            {
               btnSubmit.Text = "Clear";
            int result = AddPatientRecord();
            if (result > 0)
            {
                MessageBox.Show("Insert Successful");
                grdPatient.Update(); 
                grdPatient.Refresh();
            }
            else
                MessageBox.Show("Insert Fail");

            }
        }
        private int AddPatientRecord()
        {
            int result = 0;
            // TO DO: Codes to insert customer record
            //retrieve connection information info from App.config
            string strConnectionString = ConfigurationManager.ConnectionStrings["sacpConnection"].ConnectionString;
            //STEP 1: Create connection
            SqlConnection myConnect = new SqlConnection(strConnectionString);
            //STEP 2: Create command
            String strCommandText = "INSERT PATIENT(pFirstName, pLastName, pContact, pAddress, pCity, pZip, pNationality, pRace, pIC, pGender, pDOB, pBloodType, pEmail) "
                + " VALUES (@pFirstName,@pLastName,@pContact,@pAddress,@pCity,@pZip,@pNationality, @pRace, @pIC, @pGender, @pDOB, @pBloodType, @pEmail)";

            SqlCommand updateCmd = new SqlCommand(strCommandText, myConnect);

            updateCmd.Parameters.AddWithValue("@pFirstName", txtpFirstName.Text);
            updateCmd.Parameters.AddWithValue("@pLastName", txtpLastName.Text);
            //updateCmd.Parameters["@clientid"].Direction = ParameterDirection.Output; 
            updateCmd.Parameters.AddWithValue("@pContact", txtpContact.Text);
            updateCmd.Parameters.AddWithValue("@pAddress", txtpAddress.Text);
            updateCmd.Parameters.AddWithValue("@pCity", txtpCity.Text);
            updateCmd.Parameters.AddWithValue("@pZip", txtpZip.Text);
            updateCmd.Parameters.AddWithValue("@pNationality", txtpNationality.Text);
            updateCmd.Parameters.AddWithValue("@pRace", txtpRace.Text);
            updateCmd.Parameters.AddWithValue("@pIC", txtpIC.Text);
            updateCmd.Parameters.AddWithValue("@pGender", txtpGender.Text);
            updateCmd.Parameters.AddWithValue("@pDOB", txtpDOB.Text);
            updateCmd.Parameters.AddWithValue("@pBloodType", txtpBloodType.Text);
            updateCmd.Parameters.AddWithValue("@pEmail", txtpEmail.Text);
            // STEP 3 open connection and retrieve data by calling ExecuteReader
            myConnect.Open();
            // STEP 4: execute command
            // indicates number of record updated.
            result = updateCmd.ExecuteNonQuery();

            // STEP 5: Close
            myConnect.Close();
            return result;

        }

        private void patient_Load(object sender, EventArgs e)
        {
            LoadPatientRecords();
        }

        private void LoadPatientRecords()
        {

            //retrieve connection information info from App.config
            string strConnectionString = ConfigurationManager.ConnectionStrings["sacpConnection"].ConnectionString;
            //STEP 1: Create connection
            SqlConnection myConnect = new SqlConnection(strConnectionString);
            //STEP 2: Create command
            string strCommandText = "SELECT pFirstName, pLastName, pContact, pAddress, pCity, pZip, pNationality, pRace, pIC, pGender, pDOB, pBloodType, pEmail, pUsername, pPassword FROM Patient";

            PatientAdapter = new SqlDataAdapter(strCommandText, myConnect);

            //command builder generates Select, update, delete and insert SQL
            // statements for MedicalCentreAdapter
            SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(PatientAdapter);
            // Empty Employee Table first
            Patient.Clear();
            // Fill Employee Table with data retrieved by data adapter
            // using SELECT statement
            PatientAdapter.Fill(Patient);

            // if there are records, bind to Grid view & display
            if (Patient.Rows.Count > 0)
                grdPatient.DataSource = Patient;
        }
    }
}
Pony
  • 401
  • 3
  • 13
  • 43
  • please put only usefull code related to question don't write all of your code – Amit Bisht Jan 23 '14 at 04:01
  • Did you try calling grdPatient.DataBind() after setting the DataSource? – Karthik Kalyanasundaram Jan 23 '14 at 04:02
  • Where is my code of setting the DataSource? @Karthik Kalyanasundaram – Pony Jan 23 '14 at 04:06
  • My teacher gave me the practical codes, that doesn't refresh the datagridview after inserting!!. @Karthik Kalyanasundaram – Pony Jan 23 '14 at 04:10
  • `grdPatient.DataSource = Patient;` is the line which sets DataSource. In `if` block add this line too `grdPatient.DataBind()` – Karthik Kalyanasundaram Jan 23 '14 at 07:19
  • Like this? if (Patient.Rows.Count > 0) grdPatient.DataSource = Patient; grdPatient.DataBind(); I got error. Error 2 'System.Windows.Forms.DataGridView' does not contain a definition for 'DataBind' and no extension method 'DataBind' accepting a first argument of type 'System.Windows.Forms.DataGridView' could be found (are you missing a using directive or an assembly reference?) @Karthik Kalyanasundaram – Pony Jan 25 '14 at 19:47

9 Answers9

14

Only need to fill datagrid again like this:

this.XXXTableAdapter.Fill(this.DataSet.XXX);

If you use automaticlly connect from dataGridView this code create automaticlly in Form_Load()

starko
  • 1,150
  • 11
  • 26
  • Yours is a simple way of doing it if we are automatically connecting from DataGridView. I used your suggestion since I am automatically connecting. – nam Mar 19 '16 at 03:07
8

Try refreshing the datagrid after each insert

datagridview1.update();
datagridview1.refresh();  

Hope this helps you!

user3222297
  • 186
  • 9
  • u mean after each updateCmd.Parameters.AddWithValue line. I put that code? will try that after u get home thanks @user3222297 – Pony Jan 23 '14 at 06:06
  • You can give that after calling the function AddPatientRecord(). Or give it when you give "Insert Succesfull". – user3222297 Jan 23 '14 at 06:11
  • I added a new image. Is this how I do it? but I got error. @user3222297 – Pony Jan 25 '14 at 19:47
  • Kindly put the statements inside if loop in { } and then try it. Like this : if(result>0) { Messagebox.Show("..."); datagridview1.update(); datagridview1.refresh(); } – user3222297 Jan 27 '14 at 04:04
  • I have no errors already by following your code. I edited my codes above on my post and added a image. But the datagrid still doesn't refresh after I insert a record. I still need to reopen the form. @user3222297 – Pony Jan 27 '14 at 07:24
  • Even after clicking the ok button of Insert Successful its not refreshing the grid? – user3222297 Jan 28 '14 at 03:52
4

Use LoadPatientRecords() after a successful insertion.

Try the below code

private void btnSubmit_Click(object sender, EventArgs e)
{
        if (btnSubmit.Text == "Clear")
        {
            btnSubmit.Text = "Submit";

            txtpFirstName.Focus();
        }
        else
        {
           btnSubmit.Text = "Clear";
           int result = AddPatientRecord();
           if (result > 0)
           {
               MessageBox.Show("Insert Successful");

               LoadPatientRecords();
           }
           else
               MessageBox.Show("Insert Fail");
         }
}
Jöcker
  • 5,281
  • 2
  • 38
  • 44
Teju MB
  • 1,333
  • 5
  • 20
  • 37
3

You can set the datagridview DataSource to null and rebind it again.

private void button1_Click(object sender, EventArgs e)
{
    myAccesscon.ConnectionString = connectionString;

    dataGridView.DataSource = null;
    dataGridView.Update();
    dataGridView.Refresh();
    OleDbCommand cmd = new OleDbCommand(sql, myAccesscon);
    myAccesscon.Open();
    cmd.CommandType = CommandType.Text;
    OleDbDataAdapter da = new OleDbDataAdapter(cmd);
    DataTable bookings = new DataTable();
    da.Fill(bookings);
    dataGridView.DataSource = bookings;
    myAccesscon.Close();
}
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
0

I don't know if you resolved your problem, but a simple way to resolve this is rebuilding the DataSource (it is a property) of your datagridview. For example:

grdPatient.DataSource = MethodThatReturnList();

So, in that MethodThatReturnList() you can build a List (List is a class) with all the items you need. In my case, I have a method that return the values for two columns that I have on my datagridview.

Pasch.

Paschoali
  • 91
  • 1
  • 8
0

In the form designer add a new timer using the toolbox. In properties set "Enabled" equal to "True".

enter image description here

The set the DataGridView to equal your new data in the timer

enter image description here

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
EoinMcL
  • 85
  • 1
  • 6
0

this.donorsTableAdapter.Fill(this.sbmsDataSet.donors);

Develop4Life
  • 7,581
  • 8
  • 58
  • 76
0

I tried everything mentionned here and it all failed. What I needed to do was Thread.Sleep(1_000); between the database update and the datagridview refresh. It seems that the datagridview was refreshing before the data was updated in the database.

Maxter
  • 716
  • 7
  • 15
-1

Try below piece of code.

this.dataGridView1.RefreshEdit();