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

16

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

按照 @user3222297 的代码添加 grdPatient.Update(); 和 grdPatient.Refresh();,但在单击“插入成功”的 OK 后仍未刷新。

没有刷新

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

请只提供与问题相关的有用代码,不要写出所有的代码。 - Amit Bisht
在设置数据源后,您尝试过调用 grdPatient.DataBind() 吗? - Karthik Kalyanasundaram
我的设置DataSource的代码在哪里?@Karthik Kalyanasundaram - Pony
我的老师给了我实际的代码,但在插入后没有刷新 datagridview!!。@Karthik Kalyanasundaram - Pony
grdPatient.DataSource = Patient; 是设置数据源的行。在 if 代码块中,还需添加此行:grdPatient.DataBind() - Karthik Kalyanasundaram
这样做吗?如果(Patient.Rows.Count> 0),则grdPatient.DataSource = Patient;grdPatient.DataBind(); 我得到了错误消息。 错误2:“System.Windows.Forms.DataGridView”不包含“DataBind”的定义,也找不到接受类型为“System.Windows.Forms.DataGridView”的第一个参数的扩展方法“DataBind”(是否缺少使用指令或程序集引用?)@Karthik Kalyanasundaram - Pony
10个回答

14

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

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

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


如果我们从DataGridView自动连接,你的方法非常简单。我使用了你的建议,因为我正在自动连接。 - nam

9

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

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

希望这能帮到你!

你的意思是在每个 updateCmd.Parameters.AddWithValue 行之后添加那段代码吗?我会在你回家后尝试,谢谢 @user3222297。 - Pony
你可以在调用AddPatientRecord()函数之后提供它。或者在给出“插入成功”时提供它。 - user3222297
我添加了一个新的图片。这是我应该做的吗?但是我收到了错误提示。@user3222297 - Pony
请将语句放在 if 循环的 { } 中,然后尝试运行。 像这样:if(result>0) { Messagebox.Show("..."); datagridview1.update(); datagridview1.refresh();
}
- user3222297
我已经按照您的代码进行了修改,没有出现任何错误。我在我的帖子上编辑了我的代码并添加了一张图片。但是在我插入记录后,数据网格仍然没有刷新。我仍然需要重新打开表单。@user3222297 - Pony
即使点击“插入成功”的确定按钮,它仍然没有刷新网格? - user3222297

4
在成功插入后,使用 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
您可以将 datagridviewDataSource 设置为 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();
}

0

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


0

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

grdPatient.DataSource = MethodThatReturnList();

所以,在MethodThatReturnList()中,您可以使用所有需要的项构建一个列表(List是一个类)。在我的情况下,我有一个方法返回我datagridview上两列的值。

Pasch。


0

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


0
在表单设计器中使用工具箱添加一个新的计时器。在属性中将“Enabled”设置为“True”。

enter image description here

在计时器中将 DataGridView 设置为新数据的值

enter image description here


0
创建一个方法,并在其中调用数据表方法。以下是示例:
private void RefreshDataGridView() { 

    usrlogin = Application.OpenForms.OfType().FirstOrDefault();     
    con.ConnectionString = usrlogin.connectionString;
    DataTable data = loadinGrid(); // Assuming this method fetches data from your database

    // Clear existing rows and add the new data
    customDataGridView2.Rows.Clear();
    foreach (DataRow row in data.Rows)
    {
        string usrn = row["username"].ToString();
        string usrid = row["userid"].ToString();
        string role = "";

        switch (usrid)
        {
            case "1":
                role = "Admin";
                break;
            case "2":
                role = "Operator";
                break;
            case "3":
                role = "Authorizer";
                break;
            case "4":
                role = "Key Officer";
                break;
            default:
                role = "Unknown";
                break;
        }
        customDataGridView2.Rows.Add(false, usrn, role, usrid); // Add checkboxes, username, and userid
    }
    customDataGridView2.CellClick += customDataGridView2_CellContentClick_1;
    customDataGridView2.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
}

-1

尝试下面的代码片段。

this.dataGridView1.RefreshEdit();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接