обновление datagridview

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

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

            }
        }
    }

person bandaa    schedule 27.03.2013    source источник
comment
Я попробую еще раз. Нам нужно увидеть, где вы создаете и показываете форму frmViewBookings. Можете ли вы предоставить этот код?   -  person Rob    schedule 27.03.2013
comment
я разделил его, вверху моя форма frmBooking и внизу форма frmViewBooking... это все, что у меня есть на данный момент   -  person bandaa    schedule 27.03.2013
comment
Я понимаю это, но где-то у вас есть строка кода, похожая на: frmViewBookings newFrmViewBookings = new frmViewBookings(); новыйFrmViewBookings.Show(); можешь показать нам, где ты это делаешь?   -  person Rob    schedule 27.03.2013
comment
у меня этого нет, я просто перетащил datagridview из панели инструментов и изменил источник данных, чтобы он соответствовал источнику таблицы резервирования, которая отображает данные, хранящиеся в таблице, и обновляется только при повторном запуске программы,   -  person bandaa    schedule 27.03.2013
comment
Тогда как frmViewBookings отображается пользователю??? Вы не предоставляете достаточно информации, чтобы помочь вам решить проблему.   -  person Rob    schedule 27.03.2013
comment
кому ты рассказываешь? лол, как я уже сказал, все работает нормально в программе, кроме отображения данных, если я не выйду из программы и не запущу ее снова. но я могу добавить данные в фактическую базу данных.   -  person bandaa    schedule 27.03.2013
comment
давайте продолжим обсуждение в чате   -  person Rob    schedule 27.03.2013


Ответы (1)


Чтобы отобразить данные в вашей сетке данных, вам нужно сначала установить источник данных, который вы бы сделали следующим образом.

datagridview1.Datasource = this.usersDataSet1.Booking.DefaultView

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

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

person Faaiz Khan    schedule 27.03.2013