So I've built a GUI that loads data from an SQL Server database to the GUI's datagridview. And I trigger this event by a button called "Run".
However I want this datagridview to be refreshed every 1 minute to make sure I see the most recent entries.
To achieve this I currently use a While (true) loop, but I'm not sure if this is best practice to achieve my goal. I'd love some feedback on my code!
My current code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using static System.Net.Mime.MediaTypeNames;
namespace Broker_Monitor
{
public partial class Form1 : Form
{
// Connection string for Database
string connectionstring = "Server=x; Database=x; User Id=x; Password=x;";
// SQL Query
string query = "SELECT TOP (1000) * FROM [Database].[dbo].[Table]";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
// Button
private void button_Click(object sender, EventArgs e)
{
while (true)
{
try
{
using (var connection = new SqlConnection(connectionstring))
using (var adapter = new SqlDataAdapter(query, connection))
{
var table = new DataTable();
adapter.Fill(table);
this.datagridview.DataSource = table;
System.Threading.Thread.Sleep(60000); // sleep for 1 minute then continue the infinite loop
}
}
catch
{
MessageBox.Show("Unable to establish connection with Database!", "Warning",
MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
}
}
}
// Data grid view
private void datagridview_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
}
}