gpt4 book ai didi

c# - 需要帮助使用 ListView 中的选定项目作为 sql 查询的变量

转载 作者:行者123 更新时间:2023-11-30 17:03:51 26 4
gpt4 key购买 nike

觉得有问题
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();
}

谢谢

最佳答案

这是你需要改变的。

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();
}

}

关于c# - 需要帮助使用 ListView 中的选定项目作为 sql 查询的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18135754/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com