C#中,使用Thread新创建一个线程来查询数据库中的信息显示在控件“listView1”上,需要使用Invoke(代理名)方法来访问控件“listView1”,实例讲解
using System;
using System.Collections.Generic;
listview控件在哪里using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Threading;
namespace Frm_Clock_Event
{
public partial class Frm_Thread : Form
{
public delegate void daili();
daili dailiEvent = null;
public Frm_Thread()
{
InitializeComponent();
init();
}
public void init()
{
Btn_Select.Click += new EventHandler(Btn_Select_Click);
listView1.Left = 0;
listView1.Top = 0;
listView1.GridLines = true;
listView1.FullRowSelect = true;
listView1.View = View.Details;
listView1.Scrollable = true;
listView1.MultiSelect = false; // 不可以多行选择
listView1.HeaderStyle = ColumnHeaderStyle.Clickable;
}
void Btn_Select_Click(object sender, EventArgs e)
{
Thread thr = new Thread(Thread_dailiEvent);
thr.Start();
//新创建一个线程来访问listView1控件,而不是创建控件“listView1”的线程访问它,这是需要使用Invoke(代理名)方法来访问控件“listView1”
//SelecDB();
//throw new Exception("The method or operation is not implemented.");
}
public void Thread_dailiEvent()
{
dailiEvent = new daili(SelecDB);
if (listView1.InvokeRequired) //判断调用方对listView1控件的调用是否需要通过Invoke方法来调用
{
listView1.Invoke(dailiEvent);
}
else
{
dailiEvent(); //线程间操作无效: 从不是创建控件“listView1”的线程访问它。
}
}
//连接数据库查询信息并显示
public void SelecDB()
{
listView1.Clear();
listView1.Columns.Add("编号",100,HorizontalAlignment.Center);
listView1.Columns.Add("姓名",100,HorizontalAlignment.Center);
listView1.Columns.Add("性别", 100, HorizontalAlignment.Center);
listView1.Columns.Add("手机号", 100, HorizontalAlignment.Center);
listView1.Columns.Add("月薪", 100, HorizontalAlignment.Center);
listView1.Visible = true;
SqlConnection Conn = new SqlConnection("Server=.;DataBase=Students;UID=denglu;PWD=denglu");
SqlCommand Comm = new SqlCommand("select * from Stu_Teacher_Information",Conn);
Conn.Open();
SqlDataReader re = Comm.ExecuteR
eader();
int i = 0;
while (re.Read())
{
listView1.Items.Add(re[0].ToString());
listView1.Items[i].SubItems.Add(re[1].ToString());
listView1.Items[i].SubItems.Add(re[2].ToString());
listView1.Items[i].SubItems.Add(re[3].ToString());
listView1.Items[i].SubItems.Add(re[4].ToString());
i++;
}
Conn.Close();
Comm.Clone();
}
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论