Identify selected item Listview

Asked

Viewed 1,250 times

3

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

Remembering that my ListView has the option to select multiple lines, basically need to recover the CODIGO_PRODUTO of all lines selected to apply the 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);
        }
    }
}
  • 1

    you have to use the events SelectedIndexChanged or ItemSelectionChanged

  • Let’s assume that I have 10 products registered, with Product Code from 1 to 10, I click on the Code 5 product, how do I recover this value 5? Could I assemble a code block for me to have base?

1 answer

1

You can use the 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 using a DataGridView for that purpose, and also use a BindingList<> to popular the same. It will simplify your work.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.