We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

How to refresh sfDataGrid data/datasource

I have this code to load the data to the sfDataGrid.

    Public Sub ReloadCustomerData()
dgCustomerList.DataSource = Customers.GetAll
End Sub


I have read stuff till I am blue in the face and I must be missing something.

The mssql database table has been updated outside of my application.

How do I refresh the sfDataGrid?


7 Replies

SJ Sathiyathanam Jeyakumar Syncfusion Team March 27, 2023 12:06 PM UTC

Hi Donald,

We would like to let you know If the underlying datasource of SfDataGrid is implemented with INotifyCollectionChanged, then the SfDataGrid will automatically refresh the UI when performing data operations and runtime changes. However, if the datasource is not implemented with INotifyCollectionChanged, you will need to manually refresh the UI using the SfDataGrid.View.Refresh() method during data operations.


SfDataGrid.View.Refresh() 


It's important to note that if your collection already implements the INotifyCollectionChanged interface (such as ObservableCollection), you don't need to call the SfDataGrid.View.Refresh() method as the UI will be automatically refreshed upon any data changes.

Let us know if you need any further assistance on this. 

Regards,

Sathiyathanam



DO Donald March 27, 2023 10:20 PM UTC

I am a novice at this so allot of this does not make sense to me.


Database is MySQL.

Using a DAL class.

    Public Sub ReloadCustomerData()
        dgCustomerList.DataSource = Customers.GetAll
    End Sub

Public Shared Function GetAll() As DataTable
Dim connectionString As String = ConfigurationManager.ConnectionStrings("DatabaseConnectionString").ConnectionString

Using con = New MySqlConnection(connectionString)
Dim dataTable As New DataTable

con.Open()

Dim query As String = "SELECT `idCustomer`,`CustomerName`,`idPrimaryContact`,`DateCreated`,`DateLastModified`,`idCustomerStatus` " & _
                                "FROM `Customers`;"

Using cmd = New MySqlCommand(query, con)
Using reader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
dataTable.Load(reader)
End Using
End Using

Return dataTable
End Using
End Function






SJ Sathiyathanam Jeyakumar Syncfusion Team March 28, 2023 01:35 PM UTC

Donald,

We apologize for the inconvenience caused. We are having difficulty understanding the issue you are experiencing. To investigate the problem further, could you please provide us with the following details:

  1. Could you please explain why you attempted to refresh the datagrid?
  2. Are you experiencing a problem with the data not loading, or are you facing the same issue when changing the DataSource at runtime?
  3. Apart from the data not loading issue, are you encountering any other problems?
  4. Is it possible for you to share the entire code snippet related to the datagrid, or provide us with a reproducible sample of the issue?
  5. Alternatively, if it would be helpful, is it possible for you to share a video illustration of the problem you are experiencing?


DO Donald March 28, 2023 02:07 PM UTC

My only issue is not understanding how to refresh the data.

  1. Could you please explain why you attempted to refresh the datagrid? - Data was added to database using Customers.Add() class.
  2. Are you experiencing a problem with the data not loading, or are you facing the same issue when changing the DataSource at runtime? - Data loads fine initially, issue is only when I ADD, DELETE, OR EDIT data in database using my Customer Class.
  3. Apart from the data not loading issue, are you encountering any other problems? - Not at this time.
  4. Is it possible for you to share the entire code snippet related to the datagrid, or provide us with a reproducible sample of the issue? - I do not really have any code, as I do not know how to do it. That is why I am asking.

Example:
  • Application is running, and datagrid is loaded with data as expected. Let's say it has 10 records.
  • Record is deleted from database using my customer class.
  • Datagrid still shows same 10 records showing. 
  • this is where I am stuck, how to make the datagrid refresh and show the 9 records that are left?



SJ Sathiyathanam Jeyakumar Syncfusion Team March 29, 2023 03:01 PM UTC

Donald,

We suspect that you may have been querying the database for every data operation. While querying the database to load data into the datagrid during initial loading is acceptable, continuously querying the data source during delete scenarios can cause issues. In your case, it seems that you are attempting to remove a record from a newly queried DataTable Collection, but this new collection is not related to the already queried collection (ie.DataGrid bounded data source), as they are different instances. Therefore, only the data changes made in the new collection will be reflected.

Here we have prepared the sample and create the collection instance globally and then add and remove the data to that the global collection then it will be working properly.

public partial class Form1 : Form

{

//Global CollectionVariable Which is queried first time alone and then further runtime ADD Delete EDIT operations will be done based on this collection.

    DataTable collection;

    public Form1()

    {

        InitializeComponent();

        sfDataGrid.AutoGenerateColumns = true;

        sfDataGrid.AllowEditing = true;

        sfDataGrid.DataSource = GetAll();

          

    }

 

    public DataTable GetAll()

    {

        collection = new DataTable();

        collection.Columns.Add("ID", typeof(int));

        collection.Columns.Add("Name", typeof(string));

        collection.Columns.Add("Q1", typeof(float));

        collection.Columns.Add("Q2", typeof(float));

        collection.Columns.Add("Q3", typeof(float));

 

        collection.Rows.Add(1001, "Belgim", 872.81, 978.89, 685.90);

        collection.Rows.Add(1002, "Oliver", 978.76, 458.21, 675.99);

        collection.Rows.Add(1003, "Bernald", 548.31, 234.32, 423.44);

        collection.Rows.Add(1004, "James", 123.31, 6543.12, 978.31);

        collection.Rows.Add(1005, "Beverton", 654.33, 978.31, 654.11);

        collection.Rows.Add(1005, "Berlin", 647.33, 978.31, 423.44);

        collection.Rows.Add(1006, "Fransis", 908.55, 123.31, 675.99);

        collection.Rows.Add(1006, "Fred", 654.34, 423.44, 978.31);

        return collection;

    }

 

    private void button1_Click_1(object sender, EventArgs e)

    {

        //Global Collection Variable alone changed at runtime. We don’t change the instance

        collection.Rows.Add(1008, "FSati", 6.34, 4.44, 9.31);

    }

 

    private void button2_Click(object sender, EventArgs e)

    {

        collection.Rows.RemoveAt(0);

    }

}



To further investigate this issue, it would be helpful to share code snippets for ADD DELETE EDIT operations. By doing so, we can better understand the problem and find possible solutions.


Attachment: WindowsFormsApp1_d87fb59a.zip


DO Donald March 30, 2023 12:06 AM UTC

Here are the code snips...


Click event from delete customer buttong

            Dim result As DialogResult = MessageBox.Show("Are you sure you want to delete: " & txtCustomerName.Text & "?", "Simple ERP", MessageBoxButtons.YesNo, MessageBoxIcon.Information)
            If result = DialogResult.Yes Then
                '========================================
                ' DELETE CUSTOMER
                '========================================
                Customers.Delete(_idCustomer)


                Dim _Log As SERP_Logs = New SERP_Logs
                _Log.LogDate = Date.Now
                _Log.LogType = 1
                _Log.LogUser = ""
                _Log.LogMessage = "Customer Deleted: " & txtCustomerName.Text
                _Log.Add()


                MessageBox.Show("Customer Deleted Successully!", "Simple ERP", MessageBoxButtons.OK, MessageBoxIcon.Information)


Delete record from DataAccessLayer.dll

Public Shared Sub Delete(idCustomer As Integer)
Dim connectionString As String = ConfigurationManager.ConnectionStrings("DatabaseConnectionString").ConnectionString

Using con = New MySqlConnection(connectionString)
Dim query As String = "DELETE FROM `Customers` " & _
"WHERE `idCustomer` = @idCustomer;"

con.Open()

Using cmd = New MySqlCommand(query, con)
cmd.Parameters.Add("@idCustomer", MySqlDbType.Int32, 4).Value = idCustomer
cmd.ExecuteNonQuery()
End Using


con.Close()
End Using

End Sub


Get all records from DataAccessLayer.dll

Public Shared Function GetAll() As DataTable
Dim connectionString As String = ConfigurationManager.ConnectionStrings("DatabaseConnectionString").ConnectionString

Using con = New MySqlConnection(connectionString)
Dim dataTable As New DataTable

con.Open()

Dim query As String = "SELECT `idCustomer`,`CustomerName`,`idPrimaryContact`,`DateCreated`,`DateLastModified`,`idCustomerStatus` " & _
"FROM `Customers`;"
Using cmd = New MySqlCommand(query, con)
Using reader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
dataTable.Load(reader)
End Using
End Using

Return dataTable
End Using
End Function



VS Vijayarasan Sivanandham Syncfusion Team March 30, 2023 02:36 PM UTC

Donald,

We have analyzed the provided code snippet. We suspect that you are deleting the record from the database itself. By default, the SfDataGrid does not get notifications for these scenarios, so only the SfDataGrid doesn't get updated. However, our SfDataGrid allows you to delete the records directly with the help of the Delete key. Please refer to the below user guide documentation for more information,

UG Link: https://help.syncfusion.com/windowsforms/datagrid/datamanipulation?cs-save-lang=1&cs-lang=vb#delete-row

By default, when the record gets deleted, it will automatically update the view of the grid alone to refresh the changes. It will affect only the view of the grid and will not update the changes to the underlying source file. You could update your underlying data source file manually. It will be achievable with the help of the CollectionChanged event in SfDataGrid.View.Records. You could update the database of deleted rows by using SfDataGrid.View.Records.CollectionChanged event. Please refer to the below code snippet,

AddHandler sfDataGrid1.View.Records.CollectionChanged, AddressOf OnCollectionChanged

Private Sub OnCollectionChanged(ByVal sender As Object, ByVal e As System.Collections.Specialized.NotifyCollectionChangedEventArgs)

              'You can add your codes here to save the delete row data changes into the underlying collection or SQL Database.

End Sub


UG Link: https://help.syncfusion.com/windowsforms/datagrid/databinding?cs-save-lang=1&cs-lang=vb#collectionchanged

If this post is helpful, please consider Accepting it as the solution so that other members can locate it more quickly.


Loader.
Up arrow icon