3

认为
cmd.Parameters.AddWithValue("@name", listView1.SelectedItems );处有问题 有人对此有想法吗?

 private void Form_Load(object sender, EventArgs e)
    {
        SqlConnection cnn = new SqlConnection(tools.ConnectionString);
        SqlCommand cmd = new SqlCommand("select * from Employees",cnn);
        cnn.Open();
        SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
        while (dr.Read())
        {
            ListViewItem lvi = new ListViewItem();
            lvi.Text = dr["FirstName"].ToString();
            lvi.SubItems.Add(dr["LastName"].ToString());
            listView1.Items.Add(lvi);
        }
        cnn.Close();
    }

    private void listView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        SqlConnection cnn = new SqlConnection(tools.ConnectionString);
        SqlCommand cmd = new SqlCommand("select EmployeeId,BirthDate from Employees where FirstName = @name  ",cnn);
        cmd.Parameters.AddWithValue("@name", listView1.SelectedItems );
        cnn.Open();
        SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
        while (dr.Read())
        {
            MessageBox.Show("Id= "+dr["EmployeeID"].ToString() + "\nBirth Date= "+dr["BirthDate"].ToString());
        }
        cnn.Close();
    }

谢谢

4

2 回答 2

2

这是你需要改变的。

private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
    if(listView1.SelectedItems.Count > 0)
    {
        SqlConnection cnn = new SqlConnection(tools.ConnectionString);
        SqlCommand cmd = new SqlCommand("select EmployeeId,BirthDate from Employees where FirstName = @name  ",cnn);
        cmd.Parameters.AddWithValue("@name", listView1.SelectedItems[0].Text );
        cnn.Open();
        SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
        while (dr.Read())
        {
            MessageBox.Show("Id= "+dr["EmployeeID"].ToString() + "\nBirth Date= "+dr["BirthDate"].ToString());
        }
        cnn.Close();
    }

}
于 2013-08-08T20:49:12.120 回答
0

我会想象选定的项目是一个集合,尝试从集合中选择的项目。

于 2013-08-08T20:47:35.853 回答