C#问题
使用线程读datagrid的数据到dateset里面,要求一个在显示的之后另一个线程在读,放在同一个dateset里面,读完显示后要清空dataset.
有高手没?
写一下!
using System;
using System.Collections.Generic;
using
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using DB;
using System.Threading;
namespace SourceReadDemo
{
public partial class Form1 : Form
{
private bool flag;//用于关闭线程
private Thread thread;//定义一个线程
private bool flag1;
private Thread thread1;
public delegate void MyInvoke(DataSet ds);//定义一个委托
public Form1()
{
InitializeComponent();
}
/// <summary>
///
/// </summary>///
SqlConnection con = new SqlConnection("server=.;database=pubs;uid=sa;pwd=");
int page = 1;
private void btnNext_Click(object sender, EventArgs e)
{
flag = false;
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void button1_Click(object sender, EventArgs e)
{
flag1 = true;
flag = true;
thread = new Thread(new ThreadStart(threadProc));
thread1 = new Thread(new ThreadStart(threa1));
thread.Start();
thread1.Start();
}
//操作DataGridView
private void BindDataGridView( DataSet ds)
{
this.dataGridView1.DataSource = ds.Tables["student"];
}
//线程回调函数
private void threadProc()
{
while (flag)
{
//三秒钟一次
DataBind();
//thread.Suspend();
}
}
private void threa1()
{
while (flag1)
{
DataBind();
// Thread.Sleep(50000);
// thread1.Suspend();
}
}
private void DataBind()
{
int count = int.Parse(txtNum.Text.Trim().ToString());
DBAccess db = new DBAccess();
string tableName = txtTable.Text.Trim().ToString();
db = new DBAccess();
string row = @"select count(*) from " + tableName + "";
int RowCount = Convert.ToInt32(db.Verify(row).ToString());
//if (page * count > int.Parse(RowCount))//防止越界
//{
//
//db = new DBAccess();
//
int Acount = int.Parse(RowCount) - (page - 1) * count;
//
SqlDataAdapter sda = new SqlDataAdapter("select
top
" + Acount.ToString() + "id, name from " + tableName.ToString() + " where shij not in(select top " + count * (page - 1) + " (shij)
from " + tableName.ToString() + " order by shij)", con);
//
DataSet ds = new DataSet();
//
sda.Fill(ds, "student");
//
MyInvoke mi = new MyInvoke(BindDataGridView);
//
this.BeginInvoke(mi, new object[] { ds });
//
//ds.Clear();
//
return;
//}
//db = new DBAccess();
try
{
SqlDataAdapter sdat = new SqlDataAdapter("select
top
" + count.ToString() + " id, name from " + tableName.ToString() + " where shij not in(select top " + count * (page - 1) + " (shij)
from " + tableName.ToString() + " order by shij)", con);
if (sdat.Equals(null))
{
flag = false;
}
else
{
DataSet dss = new DataSet();
sdat.Fill(dss, "student");
MyInvoke me = new MyInvoke(BindDataGridView);
this.BeginInvoke(me, new object[] { dss });
page++;
dss.Clear();
if (page > RowCount)
{
flag = false;
flag1 = false;
}
//thread.Suspend();
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
finally
{
con.Close();
}
}
}