【问题标题】:How to refresh or show immediately in datagridview after inserting?插入后如何在datagridview中立即刷新或显示?
【发布时间】:2014-02-13 11:03:09
【问题描述】:

在所有文本框中输入数据后,点击提交按钮后,它不会立即显示在datagridview中,我需要重新打开表单才能看到新插入的行。刷新要放什么代码?

遵循@user3222297 代码。通过添加 grdPatient.Update();和 grdPatient.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;
        }
    }
}

【问题讨论】:

  • 请只放与问题相关的有用代码,不要写所有代码
  • 您是否尝试在设置 DataSource 后调用 grdPatient.DataBind()?
  • 我的数据源设置代码在哪里? @Karthik Kalyanasundaram
  • 我的老师给了我实用的代码,插入后不会刷新datagridview!!。 @Karthik Kalyanasundaram
  • grdPatient.DataSource = Patient; 是设置数据源的行。在if 块中也添加此行grdPatient.DataBind()

标签: c# button datagridview insert refresh


【解决方案1】:

尝试在每次插入后刷新数据网格

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

希望对你有帮助!

【讨论】:

  • 你的意思是在每个 updateCmd.Parameters.AddWithValue 行之后。我把那个代码?你回家后会试试谢谢@user3222297
  • 你可以在调用 AddPatientRecord() 函数后给出。或者当你给出“插入成功”时给出它。
  • 我添加了一张新图片。这是我的做法吗?但我得到了错误。 @user3222297
  • 请把语句放在 { } 中的 if 循环中,然后尝试一下。像这样: if(result>0) { Messagebox.Show("..."); datagridview1.update(); datagridview1.refresh(); }
  • 按照您的代码,我已经没有错误了。我在帖子中编辑了上面的代码并添加了一张图片。但是插入记录后数据网格仍然没有刷新。我仍然需要重新打开表格。 @user3222297
【解决方案2】:

插入成功后使用LoadPatientRecords()

试试下面的代码

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

【讨论】:

    【解决方案3】:

    我不知道您是否解决了问题,但解决此问题的一种简单方法是重建 datagridview 的 DataSource(它是一个属性)。例如:

    grdPatient.DataSource = MethodThatReturnList();

    因此,在 MethodThatReturnList() 中,您可以构建一个包含您需要的所有项目的列表(列表是一个类)。就我而言,我有一个方法可以返回我的 datagridview 上的两列的值。

    逾越节。

    【讨论】:

      【解决方案4】:

      您可以将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();
      }
      

      【讨论】:

        【解决方案5】:

        只需要像这样再次填充数据网格:

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

        如果您使用从 dataGridView 自动连接,此代码将在 Form_Load() 中自动创建

        【讨论】:

        • 如果我们从 DataGridView 自动连接,您的方法很简单。我使用了你的建议,因为我会自动连接。
        【解决方案6】:

        在表单设计器中使用工具箱添加一个新计时器。在属性中设置“启用”等于“真”。

        DataGridView 设置为等于计时器中的新数据

        【讨论】:

          【解决方案7】:

          试试下面的代码。

          this.dataGridView1.RefreshEdit();
          

          【讨论】:

            【解决方案8】:

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

            【讨论】:

              【解决方案9】:

              我尝试了这里提到的所有方法,但都失败了。 我需要做的是在数据库更新和数据网格视图刷新之间Thread.Sleep(1_000);。 似乎datagridview在数据库中更新数据之前正在刷新。

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 2012-04-27
                • 2023-04-02
                • 2015-06-23
                • 2013-09-04
                • 1970-01-01
                • 2013-08-25
                • 2021-07-03
                相关资源
                最近更新 更多