关于c# winform 异步调用数据,显示
如图,1,2,3个区根据搜索框显示不同的搜索结果。
如下是搜索方法,和调用。
- C# code
/// <summary> /// 开始搜索 /// </summary> private void startSearch() { string keys = ""; if (txtSearch.Text.Trim() == "") { MessageBox.Show("请输入要查询的内容", "提示"); return; } else { keys = HttpUtility.UrlEncode(txtSearch.Text, Encoding.GetEncoding("GB2312")); } dgv17173Data.AutoGenerateColumns = false; dgvLocalData.AutoGenerateColumns = false; //-------------本地数据-----------------// string sql = string.Format("select Id,Q,A from Question where q like '%{0}%'", rePlaceSpecialSign(txtSearch.Text.Trim())); int count; dgvLocalData.DataSource = DBhelper.ExecuteReader(sql, out count); lblCount.Text = count.ToString(); //--------------17173------------------// string url = "http://moyu.db.17173.com/default.aspx?kval=" + keys; List<Question> list = ParseIndexPage(url); dgv17173Data.DataSource = list; lbl17173Count.Text = list==null?"0":list.Count.ToString(); //百度题库 LoadBaidu(keys); }
- C# code
/// <summary> /// 搜索按钮 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnSearch_Click(object sender, EventArgs e) { startSearch(); }
如上代码,写出来之后,123个区的结果是代码加载完后同时显示的。我想实现的就是,123个区按照顺序来显示结果。
今天了解了点多线程,可是不知道怎么在这个程序上操作。求高人指点简单容易的方法。如果是多线程,请指点思路。
[解决办法]
如果是多线程操作的话就没有办法控制顺序显示了,楼主可以定义三个线程来进行三个数据的加载,我在这里写一个例子给楼主做参考,要实现在线程里访问非该线程创建的控件有2种办法,1种是忽略非当前线程创建的控件,第二种创建委托来访问窗体UI,在此采用第一种方法:
- C# code
private void button1_Click(object sender, EventArgs e) { Control.CheckForIllegalCrossThreadCalls = false; Thread thread = new Thread(new ThreadStart(LoadLocalData)); thread.Start(); } private void LoadLocalData() { //-------------本地数据-----------------// string sql = string.Format("select Id,Q,A from Question where q like '%{0}%'", rePlaceSpecialSign(txtSearch.Text.Trim())); int count; dgvLocalData.DataSource = DBhelper.ExecuteReader(sql, out count); lblCount.Text = count.ToString(); }