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

时间:2014-01-23 03:53:44

标签: c# button datagridview insert refresh

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

关注@ user3222297代码。通过添加grdPatient.Update();和grdPatient.Refresh();单击确定插入成功后仍然无法刷新。

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

9 个答案:

答案 0 :(得分:9)

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

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

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

答案 1 :(得分:4)

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

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

希望这能帮到你!

答案 2 :(得分: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 :(得分:3)

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

答案 4 :(得分:0)

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



grdPatient.DataSource = MethodThatReturnList();




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

PASCH。

答案 5 :(得分:0)

在表单设计器中使用工具箱添加新计时器。在属性中将“已启用”设置为“True”。

enter image description here

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

enter image description here

答案 6 :(得分:0)

尝试下面的代码。

this.dataGridView1.RefreshEdit();

答案 7 :(得分:0)

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

答案 8 :(得分:0)

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