If you want what was retrieved next time the form is opened create a setting under project properties. In the following simple example there is a setting LastCustomerIdentifer with a default value of -1 which indicates it has not been used.
Notes
- All code presented requires C#8 which will work with C# 9 too
- Only reason for a singleton is you mentioned using one, there really is no reason to use a singleton as static methods in a class will work just fine.
Singleton class
using System;
using System.Data.SqlClient; namespace SimpleConnectSqlServer.Classes
{
public sealed class DataOperations
{
private static string _connectionString =
"Data Source=.\sqlexpress;Initial " +
"Catalog=NorthWind2020;Integrated Security=True";
}private static readonly Lazy<DataOperations> Lazy = new(() => new DataOperations()); public static DataOperations Instance => Lazy.Value; public string CompanyName(int identifier) { using var cn = new SqlConnection { ConnectionString = _connectionString }; using var cmd = new SqlCommand { Connection = cn, CommandText = "SELECT CompanyName FROM Customers WHERE CustomerIdentifier = @Id" }; cmd.Parameters.AddWithValue("@Id", identifier); cn.Open(); return (string) cmd.ExecuteScalar(); } }
Form code
namespace SimpleConnectSqlServer
{
public partial class Form1 : Form
{
private int _iterations = 6;
public Form1()
{
InitializeComponent();
Closing += OnClosing;
Shown += OnShown;
}
private void OnShown(object? sender, EventArgs e)
{
if (Properties.Settings.Default.LastCustomerIdentifier <= -1) return;
CompanyNameLabel.Text = DataOperations.Instance.CompanyName(Properties.Settings.Default.LastCustomerIdentifier);
IdentifierTextBox.Text = Properties.Settings.Default.LastCustomerIdentifier.ToString();
}
private void OnClosing(object sender, CancelEventArgs e)
{
if (Properties.Settings.Default.LastCustomerIdentifier > -1)
{
Properties.Settings.Default.Save();
}
}
private void GetCustomerNameButton_Click(object sender, EventArgs e)
{
if (!int.TryParse(IdentifierTextBox.Text, out var id)) return;
CompanyNameLabel.Text = DataOperations.Instance.CompanyName(id);
Properties.Settings.Default.LastCustomerIdentifier = id;
}
}
}
Verify in SSMS
(SQL-Server Management Studio)