Comment rafraîchir ou afficher immédiatement dans datagridview après l'insertion?
après avoir entré les données dans toute la zone de texte, et après avoir cliqué sur le bouton Soumettre, il ne s'affichera pas immédiatement dans la vue de données, je dois rouvrir le formulaire afin de voir la nouvelle ligne insérée. Quel code mettre pour rafraîchir?
suit le code @user32297. en ajoutant grdPatient.Update (); et grdPatient.Refresh(); ne fonctionne toujours pas vous rafraîchir après je clique sur OK pour insérer le succès.
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;
}
}
}
7 réponses
utiliser LoadPatientRecords()
après une insertion réussie.
essayez le code ci-dessous
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");
}
}
il suffit de remplir de nouveau datagrid comme ceci:
this.XXXTableAdapter.Fill(this.DataSet.XXX);
si vous utilisez automaticlly connect from dataGridView ce code crée automaticlly in Form_Load ()
essayer de rafraîchir le datagrid après chaque insertion
datagridview1.update();
datagridview1.refresh();
J'espère que cela vous aidera!
vous pouvez définir le datagridview
DataSource
à null
et le relancer.
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();
}
Je ne sais pas si vous avez résolu votre problème, mais un moyen simple de résoudre ceci est de reconstruire la source de données (c'est une propriété) de votre datagridview. Par exemple:
grdPatient.DataSource = MethodThatReturnList();
ainsi, dans cette MethodThatReturnList() vous pouvez construire une liste (List est une classe) avec tous les éléments dont vous avez besoin. Dans mon cas, j'ai une méthode qui renvoie les valeurs de deux colonnes que j'ai sur mon datagridview.
Pasch.
dans le concepteur de forme Ajouter un nouveau minuteur en utilisant la boîte à outils. Dans les propriétés définies " Enabled "égale à"True".
le jeu le DataGridView
pour égaler vos nouvelles données dans le minuteur
essayez le code ci-dessous.
this.dataGridView1.RefreshEdit();