PDA

View Full Version : مشکل با قرار دادنمقدار به کنترل در thered



american_iran2006
شنبه 02 مرداد 1389, 13:58 عصر
سلام:
مشکل این کد کجاست ؟

چرا وقتی میخواد مقدار تو لیست باکس بریزه برنامه کامپایل نمی شه .

کد :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace WindowsFormsApplication6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Thread th;
private void Form1_Load(object sender, EventArgs e)
{

}
private void button1_Click(object sender, EventArgs e)
{

th = new Thread(new ThreadStart(HI));
th.Start();

}
private void HI()
{
listBox1.Items.Add("fff");
}
}
}

علت کامپایل نشدن
Cross-thread operation not valid: Control 'listBox1' accessed from a thread other than the thread it was created on.

خیلی ضروری .

jalalx
شنبه 02 مرداد 1389, 15:14 عصر
در این کد شما توسط یک thread تعریف شده، سعی در دسترسی به یک کنترل دارید که توسط thread دیگری ایجاد شده.
کوتاه ترین راه حل که توصیه نمی کنم اضافه کردن این یک خط به برنامه تونه توی تابع سازنده ی فرم!


Control.CheckForIllegalCrossThreadCalls = false; (http://msdn.microsoft.com/en-us/library/system.windows.forms.control.checkforillegalcrosst hreadcalls.aspx)