2014-01-23 3 views
6

После ввода данных во все текстовое поле и после нажатия кнопки отправки он не будет сразу отображаться в представлении datagridview, мне нужно снова открыть форму, чтобы увидеть новую вставленную строку. Какой код для обновления?Как обновить или показать сразу в datagridview после вставки?

Код отслеживания @ user3222297. добавив grdPatient.Update(); и grdPatient.Refresh(); по-прежнему не обновляется после того, как я нажму OK для вставки успешно.

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

пожалуйста, поместите только полезную код, связанный с вопросом, не пишите весь код –

+0

Вы попробуйте позвонить grdPatient.DataBind() после установки DataSource? –

+0

Где мой код настройки DataSource? @Karthik Kalyanasundaram – Pony

ответ

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

Попробуйте обновить DataGrid после каждой вставки

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

Надеется, что это помогает!

+0

u означает после каждой строки updateCmd.Parameters.AddWithValue. Я положил этот код? попробуем это после того, как вы получите домой спасибо @ user3222297 – Pony

+0

Вы можете дать это после вызова функции AddPatientRecord(). Или дайте это, когда вы дадите «Вставить Succesfull». – user3222297

+0

Я добавил новое изображение. Так я это делаю? но я получил ошибку. @ user3222297 – Pony

0

Я не знаю, если вы решили свою проблему, но и простой способ решить это восстановление DataSource (это свойство) вашего DataGridView. Например:

grdPatient.DataSource = MethodThatReturnList();

Таким образом, в этом MethodThatReturnList() вы можете создать список (список класс) со всеми элементами, которые необходимо. В моем случае у меня есть метод, который возвращает значения для двух столбцов, которые у меня есть на моем datagridview.

Pasch.

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

Только нужно заполнить DataGrid снова, как это:

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

При использовании Automaticlly подключения из DataGridView этот код создают Automaticlly в Form_Load()

+0

Ваш простой способ сделать это, если мы автоматически подключаемся к DataGridView. Я использовал ваше предложение, так как автоматически подключаюсь. – nam

0

В виде конструктора добавить новый таймер используя панель инструментов. В свойствах установлено значение «Включено» равным «True».

enter image description here

Набор в DataGridView сравняться новых данных в таймере

enter image description here

Смежные вопросы