Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

need help for using selected item from listview as a variable on sql query

Tags:

c#

think there is a problem at
cmd.Parameters.AddWithValue("@name", listView1.SelectedItems ); anybody have idea for that??

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

thanks

like image 655
onur asan Avatar asked Feb 25 '26 02:02

onur asan


1 Answers

This is what you need to change.

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

}
like image 57
Joseph Devlin Avatar answered Feb 27 '26 18:02

Joseph Devlin