我尝试使用计时器每秒连接并显示数据库到DatagridView1。 Im在C#中是新的,所以我对线程系统感到困惑。我尝试从定时器中调用munculkantabel(),并且始终返回该线程操作无效:从除创建线程之外的线程访问的控制。那么如何解决这个问题?如何线程安全调用DataGridView
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);
}
}
我尝试更换,但它说错误1不能将lambda表达式转换为键入'System.Delegate',因为它不是委托类型。怎么了? – tzudin
@tzudin尝试转换为'Delegate'(对于委托类型,编译器无法看到'System.Delegate'和'System.Action'类型是兼容的)类型。 – Richard