给你一个代码看看吧!
private void Form7_Load(object sender, System.EventArgs e)
{
string StrSQL="SELECT FenLei,ChineseName, HealthDangers, EmergencyFreatmentMeasures, LeakingEmergencyMeasures FROM wj";
this.sqlDataAdapter1.SelectCommand.CommandText=StrSQL;
this.sqlDataAdapter1.SelectCommand.Connection=this.sqlConnection1;
//打开数据库连接
this.sqlConnection1.Open();
this.sqlDataAdapter1.SelectCommand.ExecuteNonQuery();
System.Data.SqlClient.SqlDataReader MyReader=this.sqlDataAdapter1.SelectCommand.ExecuteReader();
this.listView1.View=View.Details;
for(int i=0;i<MyReader.FieldCount;i++)
{
this.listView1.Columns.Add(MyReader.GetName(i),120,HorizontalAlignment.Left);
}
while(MyReader.Read())
{
ListViewItem MyItem=new ListViewItem();
MyItem.Text=MyReader.GetString(1);
for(int j=0;j<MyReader.FieldCount-1;j++)
MyItem.SubItems.Add(MyReader.GetString(j+1));
this.listView1.Items.Add(MyItem);
}
this.sqlConnection1.Close();
}
private void button2_Click(object sender, System.EventArgs e)
{
try
{
string StrSQL="SELECT FenLei,ChineseName, HealthDangers, EmergencyFreatmentMeasures, LeakingEmergencyMeasures FROM wj WHERE ChineseName LIKE '%"+this.textBox2.Text+"%'";
this.sqlDataAdapter1.SelectCommand.CommandText=StrSQL;
this.sqlDataAdapter1.SelectCommand.Connection=this.sqlConnection1;
//打开数据库连接
this.sqlConnection1.Open();
//执行SQL命令
this.sqlDataAdapter1.SelectCommand.ExecuteNonQuery();
System.Data.SqlClient.SqlDataReader MyReader=this.sqlDataAdapter1.SelectCommand.ExecuteReader();
this.listView1.Clear();
this.listView1.View=View.Details;
for(int i=0;i<MyReader.FieldCount;i++)
{
this.listView1.Columns.Add(MyReader.GetName(i),120,HorizontalAlignment.Left);
}
while(MyReader.Read())
{
ListViewItem MyItem=new ListViewItem();
MyItem.Text=MyReader.GetString(0);
for(int j=0;j<MyReader.FieldCount-1;j++)
MyItem.SubItems.Add(MyReader.GetString(j+1));
this.listView1.Items.Add(MyItem);
}
//关闭连接
this.sqlConnection1.Close();
}
catch(Exception Err)
{
MessageBox.Show("查询数据库记录操作失败:"+Err.Message,"信息提示",
MessageBoxButtons.OK,MessageBoxIcon.Information);
//如果打开了连接,则关闭它
if(this.sqlConnection1.State==ConnectionState.Open)
{
this.sqlConnection1.Close();
}
}
}