2013-03-27 5 views
-2

У меня есть 2 формы и я не знаю, как обновить datagridview, если некоторые могут просто направить меня, пожалуйста. form1 выглядит следующим образом:Обновление datagridview

public partial class frmBooking : Form 
{ 
    //instance of sqlConnection created   
    SqlConnection con = new SqlConnection("Data Source=...."); 


    public frmBooking() 
    { 
     InitializeComponent(); 

     //sets the time selecter to a time format and selects the hours and mins only in 24 hour format. 
     TimeOfBooking.CustomFormat = "HH:mm"; 
     TimeOfBooking.Format = System.Windows.Forms.DateTimePickerFormat.Custom; 

     //combo box get data from database and updates when new customer is added 
     try 
     { 
      con.Open(); 
     } 
     catch (SqlException ex) 
     { 
      MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); 
      Application.Exit(); 
     } 

     NameOfCustomer.Items.Clear(); 

     SqlCommand cm = new SqlCommand("SELECT GroupName FROM Customer ORDER BY GroupName ASC", con); 

     try 
     { 
      SqlDataReader dr = cm.ExecuteReader(); 

      while (dr.Read()) 
      { 
       NameOfCustomer.Items.Add(dr["GroupName"]); 
      } 

      dr.Close(); 
      dr.Dispose(); 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); 

     } 


     //ends here 
    } 

     //sets the facility name so its copied from the previous(facility to be booked) form into the Facility text box 
    public void setFacility(string new_facility) 
    { 
     Facility.Text = new_facility; 
    } 

    //sets the date so its copied from the previous(facility to be booked) form into the date text box 
    public void setDate(string new_date) 
    { 
     Date.Text = new_date; 
    } 


    //adding a new customer button, redirects user to the add customer page 
    private void btnAddCust_Click(object sender, EventArgs e) 
    { 
     frmNewCustomer newCust = new frmNewCustomer(); 
     newCust.Show(); 
     this.Close(); 
    } 

    //cancel button will redirect the user to the main page 
    private void btnCancel_Click(object sender, EventArgs e) 
    { 
     Form3 frm3 = new Form3(); 
     frm3.Show(); 
     this.Close(); 
    } 

    private void frmBooking_Load(object sender, EventArgs e) 
    { 
     // TODO: This line of code loads data into the 'usersDataSet.Customer' table. You can move, or remove it, as needed. 
     this.customerTableAdapter.Fill(this.usersDataSet.Customer); 
     // TODO: This line of code loads data into the 'usersDataSet.Customer' table. You can move, or remove it, as needed. 
     this.customerTableAdapter.Fill(this.usersDataSet.Customer); 
     // TODO: This line of code loads data into the 'usersDataSet.Customer' table. You can move, or remove it, as needed. 
     this.customerTableAdapter.Fill(this.usersDataSet.Customer); 

    } 

    private void lblBookingForm_Click(object sender, EventArgs e) 
    { 

    } 

    private void btnConfirm_Click(object sender, EventArgs e) 
    { 

     //validation - if any of the mandotory fields are empty an error message will apear next to the text box 
     if (Facility.Text == "") 
     { 
      //MessageBox.Show("Please enter valid Facility, Date, Name Of Customer, Time Of Booking and Hours"); 
      errorFacility.SetError(Facility, "Enter A Facility To Book"); 
     } 
     else if (Date.Text == "") 
     { 
      errorDate.SetError(Date, "Enter A Valid Date"); 
     } 
     else if (NameOfCustomer.Text == "") 
     { 
      errorCust.SetError(NameOfCustomer, "Enter A Customer To Book"); 
     } 
     else if (TimeOfBooking.Text == "") 
     { 
      errorTime.SetError(TimeOfBooking, "Enter A Time To Book"); 
     } 
     else if (Hours.Text == "") 
     { 
      errorHours.SetError(Hours, "Enter The Hours To Book"); 
     } 

     //so if there isnt no error in the fields itll go on and add the data in to the database. 
     else 
     { 

     //instance of sqlConnection    
     SqlConnection con = new SqlConnection("Data Source=..."); 

     //instance of sqlCommand 
     String query = 
      "INSERT INTO [Booking] values ('" 
      + Facility.Text 
      + "', '" + Date.Text 
      + "', '" + NameOfCustomer.Text 
      + "', '" + TimeOfBooking.Text 
      + "', '" + Hours.Text 
      + "', '" + Paid.Text 
      + "', '" + Notes.Text 
      + "')"; 

     SqlCommand cmd = new SqlCommand(query, con); 
     con.Open(); 
     cmd.ExecuteNonQuery(); 


     //query executed correcty or not 
     con.Close(); 

      MessageBox.Show("Sucessfully Booked"); 

      Form3 mainPage = new Form3(); 
      mainPage.Show(); 
      this.Close(); 
     } 
    } 
    }} 

Это - форма, которую я использую, чтобы добавить бронь. Вторая форма у меня есть одна с DataGridView, который я хочу обновить, если заказ сделан код, который выглядит следующим образом:

 public partial class frmViewBookings : Form 
     { 
      public frmViewBookings() 
      { 
       InitializeComponent(); 
      } 

      private void btnClose_Click(object sender, EventArgs e) 
      { 
       Form3 mainpage = new Form3(); 
       mainpage.Show(); 
       this.Close(); 
      } 

      private void frmViewBookings_Load(object sender, EventArgs e) 
      { 
       // TODO: This line of code loads data into the 'usersDataSet1.Booking' table. You can move, or remove it, as needed. 
       this.bookingTableAdapter.Fill(this.usersDataSet1.Booking); 

      } 
     } 
    } 
+0

Я попробую еще раз. Нам нужно посмотреть, где вы создаете и показать свою форму frmViewBookings. Можете ли вы предоставить этот код? – Rob

+0

Я разделил его, верхняя часть - моя форма frmBooking и нижняя форма frmViewBooking ... это все, что у меня есть до сих пор – bandaa

+0

Я это понимаю, но где-то у вас есть строка кода, которая похожа на: frmViewBookings newFrmViewBookings = new frmViewBookings(); newFrmViewBookings.Show(); можете ли вы показать нам, где вы это делаете? – Rob

ответ

0

Для отображения данных на вашем DataGrid вы должны установить это Datasource первый, который вы могли бы сделать, как этот

datagridview1.Datasource = this.usersDataSet1.Booking.DefaultView

Всякий раз, когда вы хотите обновить его, вы просто должны заполнить ваш TableAdapter снова и установить источник данных вашего GridView к нему.

(Создайте отдельный способ для загрузки datagridview)