日期:2014-05-18  浏览次数:20975 次

为甚么下面代码在listview内显示不了数据库内容!各位大仙帮帮忙啊?

  public Form1()
  {
  SqlCommand sqlCommand;
  SqlConnection sqlConnection;

  string cn = "Server=ELVIS-PC;Initial Catalog=学生管理数据库; User ID=sa; Password=12345";
  sqlConnection=new SqlConnection(cn); 
  string sql= "select * from 学生表 "; 
  sqlCommand=new SqlCommand(sql,sqlConnection);
  sqlConnection.Open();
   
  DataSet ds = new DataSet();
  SqlDataAdapter da = new SqlDataAdapter(sql, sqlConnection);
  SqlCommandBuilder cb = new SqlCommandBuilder(da);
  da.Fill(ds);
  try
  {
   

  // ListViewItem[] l = new ListViewItem[ds.Tables[0].Rows.Count];


  ListViewItem l = null;
   
  foreach (DataRow row in ds.Tables[0].Rows)
  {


  l = new ListViewItem(row["学号"].ToString());
  l.SubItems.Add(row["姓名"].ToString());

  l.SubItems.Add(row["性别"].ToString());
  l.SubItems.Add(row["年龄"].ToString());
  l.SubItems.Add(row["系别"].ToString());
  l.SubItems.Add(row["班级"].ToString());
  listView1.Items.Add(l);

  }
  }
  catch
  {
  }
   


   
   
   
   
   
  InitializeComponent();

  }

   
   
   
  }
}


------解决方案--------------------
探讨

首先看你读取数据成功没?
在看你的绑定代码有没问题

------解决方案--------------------
如果只是读,可以这样
 public Form1()
{
SqlCommand sqlCommand;
SqlConnection sqlConnection;

string cn = "Server=ELVIS-PC;Initial Catalog=学生管理数据库; User ID=sa; Password=12345";
sqlConnection=new SqlConnection(cn);
string sql= "select * from 学生表 ";
sqlCommand=new SqlCommand(sql,sqlConnection);
sqlConnection.Open();
 SqlDataReader jr = sqlCommand.ExecuteReader();
while (jr.Read() == true)
{
item = listView1.Items.Add(jr[0].ToString());

item.SubItems.Add(jr[1].ToString());
item.SubItems.Add(jr[2].ToString());
item.SubItems.Add(jr[3].ToString());
item.SubItems.Add(jr[4].ToString());
item.SubItems.Add(jr[5].ToString());
 }
jr.Close();
sqlConnection.Close();