将数据从数据库中读到 listview 中出错,不知道是什么错误,请各位帮忙看看
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;
namespace 学生信息管理系统
{
public partial class frmCollege : Form
{
SqlConnection sqlCon = new SqlConnection();
SqlCommand sqlCmd = new SqlCommand();
public frmCollege()
{
InitializeComponent();
}
private void frmCollege_Load(object sender, EventArgs e)
{
sqlCon.ConnectionString = "server=87SZ5ANSFFFDKQF\\MYSQL2008;database=db_SMIS;uid=sa;pwd=abc34112519941102238x"; //连接数据库
sqlCon.Open();
MessageBox.Show("成功连接上数据库");
// 测试是否连接上数据库
// this.btnSelete_Click(sender, e);
Fresh();
}
private void btnSelete_Click(object sender, EventArgs e)
{
}
private void btnAdd_Click(object sender, EventArgs e)
{
if (sqlCon.State == ConnectionState.Open)
sqlCon.Close();
sqlCon.Open();
= "select count(*) from tb_College where CName='" + this.txtCname.Text + "'";
sqlCmd.Connection = sqlCon;
int i = Convert.ToInt32(sqlCmd.ExecuteScalar());
if (i > 0)
{
MessageBox.Show("院系信息已经添加过,请不要重复添加!");
return;
}
= "insert into tb_College values('" + this.txtCname.Text + "','" + this.txtPresident.Text + "')";
sqlCmd.ExecuteNonQuery();
MessageBox.Show("院系信息已经添加成功!");
Fresh();
}
public void Fresh()
{
if (sqlCon.State == ConnectionState.Open)
sqlCon.Close();
sqlCon.Open();
sqlCmd.Connection = sqlCon;
= "select * from tb_College";
SqlDataReader sdr = sqlCmd.ExecuteReader();
while (sdr.Read())
{
ListViewItem lv = new ListViewItem(sdr[0].ToString());
lv.SubItems.Add(sdr[1].ToString());
lv.SubItems.Add(sdr[2].ToString());
}//在读入数据时出错。无法将数据读到listview中
}
//刷新操作
}
}
数据库语句:
--建立学院表
Create table tb_College
(
CId int identity(1,1)primary key,
CName varchar(20) not null,
CPresident varchar(15)
)
insert into tb_College values('哲学与社会发展学院','李静')
insert into tb_College values('经济与金融学院','金其山')
insert into tb_College values('计算机学院','陈诚' )