winform+devExpress+gridControl 数据绑定
- 0.工具箱->新建dev控件—>引用dev控件dll
- 1.将gridcontrol拖入页面
- 2.页面拖入容器控件,将girdcontrol加入此容器
groupBox1.Controls.Add(gc_Main);
- 3.生成一个数据源datatable
dataTable = new DataTable();
dataTable.Columns.Add("Name", typeof(string));
dataTable.Columns.Add("Age", typeof(int));
dataTable.Columns.Add("Gender", typeof(string));
DataRow dataRow = dataTable.NewRow();
dataRow["Name"] = "李一";
dataRow["Age"] = 20;
dataRow["Gender"] = "男";
dataTable.Rows.Add(dataRow);
dataRow = dataTable.NewRow();
dataRow["Name"] = "张二";
dataRow["Age"] = 22;
dataRow["Gender"] = "女";
dataTable.Rows.Add(dataRow);
- 4.绑定此数据库到gridcotrol
gc_Main.BindingContext = new BindingContext();
gc_Main.DataSource = dataTable;
gc_Main.ForceInitialize();
- 5.修改列名
var gv = (GridView)gc_Main.MainView;
gv.Columns["Name"].Caption = "姓名";
gv.Columns["Age"].Caption = "年龄";
gv.Columns["Gender"].Caption = "性别";
- 6.模拟更新【更新datatable界面自动更新,有点wpf的影子】
var dueTime = 1000; // 首次执行延迟时间
var interval = 5 * 1000; // 后续执行间隔时间
mytimer = new System.Threading.Timer(
callback: (st) =>
{
RandomData();
},
state: null,
dueTime: dueTime,
period: interval);
void RandomData()
{
for (int i = 0; i < dataTable.Rows.Count; i++)
{
var data = rd.Next(0, 100);
dataTable.Rows[i]["Name"] = "name:-" + data.ToString();
dataTable.Rows[i]["Age"] = data;
}
}
- 7.计数timer模拟更新
//timer封闭
public class Repeater
{
private System.Threading.Timer _timer = null;
public Repeater(Action<object> callback, object state)
{
TimerCallback tcb = (s) => callback(s);
_timer = new System.Threading.Timer(tcb, state, 0, 5000);
}
public void Completed()
{
if (_timer!=null)
{
var timerDisposed = new ManualResetEvent(false);
_timer.Dispose(timerDisposed);
timerDisposed.WaitOne();
timerDisposed.Dispose();
}
}
}
//计数timer
Counter counter = new Counter();
var re = new Repeater((a) =>
{
if (a is Counter ct)
{
RandomData();
if (ct.Count == 5)
{
UpdateControl(label1, "5次任务执行结束");
return;
}
ct.Count++;
//CheckForIllegalCrossThreadCalls = false;
//label1.Text = $"执行次数:{ct.Count}";
var txt = $"执行次数:{ct.Count}";
UpdateControl(label1, txt);
}
}, counter);
//控件Invoke.不推荐使用CheckForIllegalCrossThreadCalls = false
private void UpdateControl(Control ctl, string txt)
{
if (ctl != null && ctl.InvokeRequired)
{
ctl.Invoke((MethodInvoker)delegate
{
ctl.Text = txt;
});
}
}
努力到无能为力,拼搏到感动自己