Question:
I have a ListView
that loads values from my database.
I would like to know how I can identify the selected item so that I can retrieve the value of the CODIGO_PRODUTO
field and make an UPDATE/DELETE
in the database.
Remembering that my
ListView
has the option to select multiple lines, basically I need to retrieve theCODIGO_PRODUTO
of all selected lines to apply theDELETE
.
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);
}
}
}
Answer:
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 a DataGridView
for this purpose, and also use a BindingList<>
to populate it. It will simplify your work.