简体   繁体   English

插入后如何在datagridview中立即刷新或显示?

[英]How to refresh or show immediately in datagridview after inserting?

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.在所有文本框中输入数据后,单击提交按钮后,它不会立即显示在 datagridview 中,我需要重新打开表单才能看到新插入的行。 What code to put in for refresh?输入什么代码刷新?

Followed @user3222297 code.遵循@user3222297 代码。 by adding grdPatient.Update();通过添加 grdPatient.Update(); and grdPatient.Refresh();和 grdPatient.Refresh(); still doesn't get refreshed after i click the OK for insert successful.单击确定插入成功后,仍然没有刷新。

没有刷新

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

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()如果您使用从 dataGridView 自动连接此代码在 Form_Load() 中自动创建

Try refreshing the datagrid after each insert每次插入后尝试刷新数据网格

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

Hope this helps you!希望这对你有帮助!

Use LoadPatientRecords() after a successful insertion.成功插入后使用LoadPatientRecords()

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

You can set the datagridview DataSource to null and rebind it again.您可以将datagridview DataSource设置为null并再次重新绑定。

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

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.我不知道你是否解决了你的问题,但解决这个问题的一个简单方法是重建你的 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.因此,在 MethodThatReturnList() 中,您可以使用您需要的所有项目构建一个列表(列表是一个类)。 In my case, I have a method that return the values for two columns that I have on my datagridview.就我而言,我有一个方法可以返回我在 datagridview 上的两列的值。

Pasch.帕施。

In the form designer add a new timer using the toolbox.在表单设计器中使用工具箱添加一个新计时器。 In properties set "Enabled" equal to "True".在属性中设置“启用”等于“真”。

在此处输入图片说明

The set the DataGridView to equal your new data in the timerDataGridView设置为等于计时器中的新数据

在此处输入图片说明

试试下面的一段代码。

this.dataGridView1.RefreshEdit();

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

I tried everything mentionned here and it all failed.我尝试了这里提到的所有内容,但都失败了。 What I needed to do was Thread.Sleep(1_000);我需要做的是Thread.Sleep(1_000); between the database update and the datagridview refresh.在数据库更新和 datagridview 刷新之间。 It seems that the datagridview was refreshing before the data was updated in the database.在数据库中更新数据之前,datagridview 似乎正在刷新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM