Identify selected item ListView

1

I have ListView which loads values from my database. I would like to know how to identify the selected item so that I can retrieve the value of the CODIGO_PRODUTO field and make a UPDATE/DELETE in the database.

  

Remembering that my ListView has the option of selecting multiple rows, I basically need to retrieve the CODIGO_PRODUTO of all rows selected to apply DELETE .

private DataSet _dataSet;
private SqlDataAdapter _dataAdapterProducts;

public void getDados()
{
    SqlConnection conn = new SqlConnection(strConnection);
    string strSql = "SELECT * FROM PRODUTOS";
    conn.Open();
    try
    {
        _dataSet = new DataSet();
        _dataAdapterProducts = new SqlDataAdapter(strSql, conn);
        _dataAdapterProducts.Fill(_dataSet, "PRODUTOS");
    }
    catch (Exception ex)
    {
        MessageBox.Show("Erro: " + ex.Message.ToString(), "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

private void carregaLista()
{
    getDados();

    DataTable dtable = _dataSet.Tables["PRODUTOS"];
    lvEstoque.Items.Clear();
    for(int i = 0; i < dtable.Rows.Count; i++)
    {
        DataRow drow = dtable.Rows[i];
        if(drow.RowState != DataRowState.Deleted)
        {
            ListViewItem lvItem = new ListViewItem(drow["CODIGO_PRODUTO"].ToString());
            lvItem.SubItems.Add(drow["DESCRICAO"].ToString());
            lvItem.SubItems.Add(drow["QUANTIDADE"].ToString());
            lvItem.SubItems.Add(drow["VALOR_INICIAL"].ToString());
            lvItem.SubItems.Add(drow["VALOR_FINAL"].ToString());
            lvItem.SubItems.Add(drow["LUCRO"].ToString());
            lvEstoque.Items.Add(lvItem);
        }
    }
}
    
asked by anonymous 30.05.2018 / 03:36

1 answer

0

You can use SelectedIndexChanged . Example:

private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (listView1.SelectedItems.Count > 0)
    {
        MessageBox.Show("Código do produto escolhido: " + listView1.SelectedItems[0].SubItems[0].Text);
    }
}

But I recommend that you use DataGridView for this purpose, and also use BindingList<> to make it popular. It will simplify your work.

    
31.05.2018 / 05:17