混淆了如何填充listview

时间:2014-06-16 13:11:42

标签: c# listview

我有一个包含2列的表:usernameage。我想要做的是使用来自数据库的数据填充ListView。我想我错过了一些东西,因为每次加载表单时ListView都是空的。我注意到调试时DataReader的属性HasRows返回 false

  void populate()
    {  
        SqlCommand cmd = new SqlCommand("select * from users ", con);
        dr = cmd.ExecuteReader();

        while (dr.Read())
        {
            ListViewItem lvi = new ListViewItem(dr[0].ToString());
            lvi.SubItems.Add(dr[1].ToString());
            listView1.Items.Add(lvi);
        }

        dr.Close();
        dr.Dispose();
    }

   private void button1_Click(object sender, EventArgs e)
        {
            using (con = new SqlConnection("server=.\\sqlepxress;database=Projects;Integrated Security=sspi")) {

                try
                {
                      con.Open();
                     populate();

                }
                catch (SqlException x )
                {

                    MessageBox.Show(x.Message);
                }

            }
        }

1 个答案:

答案 0 :(得分:0)

您的连接字符串无效,请尝试:

con = new SqlConnection("Data Source=....;Initial Catalog=..;Connect Timeout=15;Integrated Security=sspi";

OR(如果Windows认证有问题:)

 new SqlConnection("Data Source="+...+";Initial Catalog=Projects;User id="+user+";Password="+pass+";Connect Timeout=15;Integrated Security=false");