简体   繁体   中英

Refresh or show immediately in datagridview after inserting

I know it's been asked many times here in SOF but i assure you i tried everything like .refresh, .update, call the method after the insertion etc. but still nothing happen i need to refresh my user control again just to see the new data change in datagridview. I'm pretty new in implementing MVC pattern in Windows Form. Below these code i remove some of my code like for inserting because there's no problem with that. I hope someone would be able to Help me.

View:

public partial class Update : Form
{
    private Customer _customer;
    public Update(Customer customer)
    {
        InitializeComponent();
        new UpdateController(this);
        _customer = customer;
        CustomPicturebox.Circle(PreviewImage);
        LoadCustomer();
    }
}

Model:

public class Customer
{

Connection Con = new Connection();
    private readonly string _date = DateTime.Now.ToString("dddd, dd MMMM yyyy");
    private readonly string _setDateId = DateTime.Now.ToString("yyyy");
    //Get the Customer Fields
    public DataTable DataTable = new DataTable();
    public DataView DataView = new DataView();

    public string _customerId { get; set; }
    public string _imagePath { get; set; }
    public string _firstName { get; set; }
    public string _middleName { get; set; }
    public string _lastName { get; set; }
    public string _extensionName { get; set; }
    public string _gender { get; set; }
    public string _contactNumber { get; set; }
    public string _email { get; set; }
    public string _homeAddress { get; set; }
    public string _searchCustomer { get; set; }

    public Customer()
    {
    }
    public Customer
    (
        string customerID,
        string imagePath,
        string firstName,
        string middleName,
        string lastName,
        string extensionName,
        string gender,
        string contactNumber,
        string email,
        string homeAddress
    )
    {
        _customerId     = customerID;
        _imagePath      = imagePath;
        _firstName      = firstName;
        _middleName     = middleName;
        _lastName       = lastName;
        _extensionName  = extensionName;
        _gender         = gender;
        _contactNumber  = contactNumber;
        _email          = email;
        _homeAddress    = homeAddress;
     }
    public void GetID(string customerID)
    {
        using (var cmd = new SqlCommand("usp_GetCustomerID", Con.GetConnection()))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@customerID", customerID);
            using (var reader = cmd.ExecuteReader())
            {
                if (reader.Read())
                {
                    _customerId    = reader["CustomerID"].ToString();
                    _imagePath     = reader["ImagePath"].ToString();
                    _firstName     = reader["FirstName"].ToString();
                    _middleName    = reader["MiddleName"].ToString();
                    _lastName      = reader["LastName"].ToString();
                    _extensionName = reader["ExtensionName"].ToString();
                    _gender        = reader["Gender"].ToString();
                    _contactNumber = reader["ContactNumber"].ToString();
                    _email         = reader["Email"].ToString();
                    _homeAddress   = reader["HomeAddress"].ToString();
                }
                reader.Close();
            }
            return;
        }
    }
    public void GetCustomerList(DataGridView customerList)
    {
        using (var cmd = new SqlCommand("usp_GetCustomer", Con.GetConnection()))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            using (var sda = new SqlDataAdapter(cmd))
            {
                sda.Fill(DataTable);
                var bsource = new BindingSource { DataSource = DataTable };
                customerList.DataSource = bsource;
            }
        }
        return;
    }
    public bool IsUpdated()
    {
        using (var cmd = new SqlCommand("usp_UpdateCustomer", Con.GetConnection()))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@customerID", _customerId);
            cmd.Parameters.AddWithValue("@imagePath", _imagePath);
            cmd.Parameters.AddWithValue("@firstName", _firstName);
            cmd.Parameters.AddWithValue("@middleName", _middleName);
            cmd.Parameters.AddWithValue("@lastName", _lastName);
            cmd.Parameters.AddWithValue("@extensionName", _extensionName);
            cmd.Parameters.AddWithValue("@gender", _gender);
            cmd.Parameters.AddWithValue("@contactNumber", _contactNumber);
            cmd.Parameters.AddWithValue("@email", _email);
            cmd.Parameters.AddWithValue("@homeAddress", _homeAddress);
            cmd.ExecuteNonQuery();
            return true;
        }
    }
}

Controller:

 class DisplayController
{
    private Connection Con = new Connection();
    private Customer Customer = new Customer();
    private Display _display;

    public DisplayController(Display display)
    {
        _display = display;
        Initialize();
        Customer.GetCustomerList(_display.customerList);
    }
    public void Initialize()
    {
        _display.search.TextChanged += Search_TextChanged;
        _display.customerList.CellClick += CustomerList_CellClick;
    }
    private void CustomerList_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        if (e.RowIndex >= 0)
        {
            var row = _display.customerList.Rows[e.RowIndex];
            Customer.GetID(row.Cells["ID"].Value.ToString());
            DimBackground overlay = new DimBackground(new Update(Customer));
            overlay.Show();
        }
    }
}

Controller of my Update form:

class UpdateController
{
    private Update _update;
    private Customer _customer;
    private Display _display = new Display();
    public UpdateController(Update update)
    {
        _update = update;
        Initialize();
    }

    public void Initialize()
    {
        _update.GetUpdateButton.Click += GetUpdateButton_Click;
        _update.GetBrowseButton.Click += GetBrowseButton_Click;
    }

    private void GetBrowseButton_Click(object sender, EventArgs e)
    {
        using (OpenFileDialog ofd = new OpenFileDialog())
        {
            ofd.Filter = "Image Files (*.jpg;*.jpeg;.*.png; | *.jpg;*.jpeg;.*.png;)";
            ofd.FilterIndex = 1;
            ofd.Multiselect = false;
            ofd.Title = "Select Image File";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                _update.Imagepath = ofd.FileName;
                _update.GetImage.Image = Image.FromFile(_update.Imagepath);
            }
        }
    }
    private void GetUpdateButton_Click(object sender, EventArgs e)
    {
        _customer = new Customer
        (
           _update.LblCustomerID.Text,
           _update.Imagepath,
           _update.GetFirstName().Text,
           _update.GetMiddleName().Text,
           _update.GetLastName().Text,
           _update.GetExtensionName().Text,
           _update.GetGender().Text,
           _update.GetContactNumber().Text,
           _update.GetEmail().Text,
           _update.GetAddress().Text
        );
        if
        (
            string.IsNullOrWhiteSpace(_update.GetFirstName().Text) ||
            string.IsNullOrWhiteSpace(_update.GetLastName().Text) ||
            string.IsNullOrWhiteSpace(_update.GetGender().Text) ||
            string.IsNullOrWhiteSpace(_update.GetAddress().Text)
        )
        {
            CustomMessageBox.Message("Please Input the Required Fields", CustomMessageBox.MessageType.Warning);
        }
        else
        {
            var result = _customer.IsUpdated() ? true : false;
            CustomMessageBox.Message("Updated!", CustomMessageBox.MessageType.Update);
            _customer.GetCustomerList(_display.customerList);
        }
    }
}

You could create a public method of filling DataGridView and call function in insertion method.

Like this

 public DataTable Table()
    {
        try
        {
            connectionString = "Data Source = Your Data source ";
            connection = new SQLiteConnection(connectionString);
            query = "SELECT * From Table";
            connection.Open();
            adapter = new SQLiteDataAdapter(query, connection);
            dataTable = new DataTable();
            adapter.Fill(dataTable);
            connection.Close();
            return dataTable;
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
            return null;
        }
    private void FillDataGrid()
    {
        dataTable = Table();
        dataGridView.DataSource = dataTable;
    }

And call this FillDataGrid() at end of your insertion/update method.

You should set the dataTable as the datasource.

public void GetCustomerList(DataGridView customerList)
{
    using (var cmd = new SqlCommand("usp_GetCustomer", Con.GetConnection()))
    {
        cmd.CommandType = CommandType.StoredProcedure;
        using (var sda = new SqlDataAdapter(cmd))
        {
            sda.Fill(dtTable);
            customerList.DataSource = dtTable ;
        }
    }
    return;
}

Edit :Try to avoid naming the DataTable as "DataTable" Use dtTable instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM