em gặp một cái lỗi như này khi dùng Parallel mong các anh chỉ giúp
Cross-thread operation not valid: Control 'cmbtrangthai' accessed from a thread other than the thread it was created on.
Code:
// hàm này là đọc thông tin tài khoản từ file xml
private void laythongtintaikhoan()
{
TaiKhoanBE taikhoan = new TaiKhoanBE();
TaiKhoanBL tkxuly = new TaiKhoanBL();
//dog nay de load xml trong debug ne
taikhoan = tkxuly.docdulieu(Environment.CurrentDirectory + "/TaiKhoan.xml");
Taikhoan = taikhoan.Taikhoan;
Idtochuc=Convert.ToInt32(taikhoan.Idtochuc.ToString());
Idmucquanly = Convert.ToInt32(taikhoan.Idmucquanly.ToString());
}
// hiển thị các thông tin tương ứng vói tài khoản đăng nhập
private void hienthidonvi()
{
laythongtintaikhoan();
DataTable dt = new DataTable();
daToChuc dToChuc = new daToChuc();
dToChuc.ToChuc.idCapTren = _idtochuc;
dToChuc.ToChuc.idMucQuanLy = _idmucquanly;
dToChuc.ToChuc.idTrangThai = (int)daTrangThaiHoatDong.eTrangThaiHoatDong.Hoạt_Động;
dt.Columns.Add("Ma", typeof(int));
dt.Columns.Add("Ten", typeof(string));
DataTable dt1 = new DataTable();
dt1 = dToChuc.DanhSach_DDL(true);
dt = dt1.Clone();
DataRow r = dt.NewRow();
r["Ma"] = dt1.Rows[0]["Ma"];
r["Ten"] = dt1.Rows[0]["Ten"];
dt.Rows.Add(r);
for (int i = 1; i < dt1.Rows.Count; i++)
{
int j = 0;
try
{
j = Convert.ToInt32(dt1.Rows[i]["Ma"].ToString());
}
catch { }
daToChuc dToChuc2 = new daToChuc();
dToChuc2.ToChuc.idCapTren = j;
dToChuc2.ToChuc.idMucQuanLy = _idmucquanly;
dToChuc2.ToChuc.idTrangThai = (int)daTrangThaiHoatDong.eTrangThaiHoatDong.Hoạt_Động;
DataTable dt2 = new DataTable();
dt2 = dToChuc2.DanhSach_DDL(true);
DataTable dtUnion = dt.AsEnumerable().Union(dt2.AsEnumerable()).CopyToDataTable<DataRow>();
dt = dtUnion;
}
cmbdonvi.Properties.DataSource = dt;
cmbdonvi.Properties.DisplayMember = "Ten";
cmbdonvi.Properties.ValueMember = "Ma";
cmbdonvi.ItemIndex = 0;
}
// lấy danh mục trạng thái từ csdl sql server
private void hienthitrangthai()
{
daTrangThaiSoLieu tt = new daTrangThaiSoLieu();
cmbtrangthai.Properties.DataSource = tt.DanhSachTrangThaiSoLieu();
cmbtrangthai.Properties.DisplayMember = "TenTrangThai";
cmbtrangthai.Properties.ValueMember = "ID";
cmbtrangthai.ItemIndex = 0;
}
private void khoitao()
{
txttungay.Text = DateTime.Now.ToString("dd/MM/yyyy");
txtdenngay.Text = DateTime.Now.ToString("dd/MM/yyyy");
Parallel.Invoke(
() =>
{
laythongtintaikhoan();
hienthidonvi();
},
() =>
{
hienthitrangthai();
}
);
}
private void FormDonHangNhanTuDieuTin_Load(object sender, EventArgs e)
{
khoitao();
hienthidulieu();
}