I try to connect and show database to DatagridView1 every second using timer. Im new in C# so I confuse about threading system. I try to call munculkantabel() from timer and it is always return that Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on. So How to fix this code?
public void buattimer()
{
System.Timers.Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed += new ElapsedEventHandler(backgroundWorker1_DoWork);
aTimer.Interval = 1000;
aTimer.Enabled = true;
}
public void backgroundWorker1_DoWork(object source, ElapsedEventArgs e)
{
Thread thh = new Thread(munculkantabel);
thh.Start();
}
string constring = "datasource=localhost;port=3306;username=root;password=;convert zero datetime=True";
public void munculkantabel()
{
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(" select * from konsentrasi.okedeh ;", conDataBase);
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmdDataBase;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bSource = new BindingSource();
bSource.DataSource = dbdataset;
dataGridView1.DataSource = bSource;
sda.Update(dbdataset);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}