日期:2014-05-19  浏览次数:21210 次

多线程绑定DataGridView的问题
单击Button5绑定DataGridView,代码如下:
delegate   void   MyDeletegate();
string   connString   =   "server=.;uid=sa;pwd=speed;database=Northwind ";

private   void   button5_Click(object   sender,   EventArgs   e)
{
        Thread   t   =   new   Thread(new   ThreadStart(ThreadBind));
        t.Name   =   "NewThread ";
        t.Start();                        
}

private   void   ThreadBind()
{
          this.BeginInvoke(new   MyDeletegate(BindGrid));                        
}

private   void   BindGrid()
{
          SqlConnection   sqlconn   =   new   SqlConnection(connString);
          sqlconn.Open();

            SqlDataAdapter   adp   =   new   SqlDataAdapter( "SELECT   *   FROM   Products ",   sqlconn);
            SqlCommandBuilder   sqlcomm   =   new   SqlCommandBuilder(adp);

            DataSet   ds   =   new   DataSet();
            adp.Fill(ds);
            this.dataGridView1.DataSource   =   ds.Tables[0];
            sqlconn.Close();
}


现在的问题是绑定DataGridView的时候界面还是处于假死状态,应该怎么样做才能保证界面不是假死呢?

------解决方案--------------------
up
------解决方案--------------------
我觉得你可以使用BackgroundWorker后台线程来做,异步调用数据。
待RunWorkerCompleted再给控件加载数据。
你直接用线程访问控件这种方法是不安去的。这个msdn文档里面有做说明。
所以微软搞了个BackgroundWorker,我觉得这个可以。
你试试看。

------解决方案--------------------

public partial class frmUserManger :  BaseForm
{
public frmUserManger()
{
InitializeComponent();
}
Tb_Employee ltb = null;

private BackgroundWorker bg = new BackgroundWorker();

DataTable dtcbo ;

private void frmUserManger_Load(object sender, EventArgs e)
{
ltb = new Tb_Employee();
BindGridView();

bg.DoWork += new DoWorkEventHandler(bg_DoWork);
bg.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bg_RunWorkerCompleted);
bg.RunWorkerAsync();
}

void bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
cboType.DataSource = dtcbo;
cboType.DisplayMember = "Value ";
cboType.ValueMember = "UID ";
}

void bg_DoWork(object sender, DoWorkEventArgs e)
{
DataTable dt = new clsStandardCode().GetStandardCodeList( "subkind ");
DataTable dt2 = new clsStandardCode().GetStandardCodeList( "department ");

DataTable dttemp = dt.Copy();
dttemp.Merge(dt2, true);
dtcbo = dttemp;
}

private void BindGridView()