How to change the Listbox Index to 1?

Asked

Viewed 35 times

0

Citation

I would like to add names to a listbox, put a NumericUpDown to associate how many dependent names will be added at most, depending on the number the user enters, and a txtbox to add names and a button to add to listbox, how can I do so so that if 0 dependents are placed, no name can be added, and if a higher value for example 2 can be added only 2 names in the listbox.

I tried that way, but it didn’t work:

private void btn_AdcNomedep_Click(object sender, EventArgs e)
{


    if (numUpDown_Dependentes.Value > 0 && numUpDown_Dependentes.Value >= listbox_NomesDep.Items.Count)
    {
        if (!listbox_NomesDep.Items.Contains(tb_NomeDep.Text))
        {
            listbox_NomesDep.Items.Add(tb_NomeDep.Text);
            tb_NomeDep.Clear();
            tb_NomeDep.Focus();
        }
        else
        {
            MessageBox.Show("Item já existente!", "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Information);
            tb_NomeDep.Clear();
            tb_NomeDep.Focus();
        }

    }
    else
    {
        MessageBox.Show("O número de dependentes já foi preenchido!", tb_NomeDep.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
    }

}

1 answer

1


You haven’t said exactly what mistake or problem you’re having. I simulated your code here on my side and the only mistake I found was that this condition allows you to add an extra item to the listbox

if (numUpDown_Dependentes.Value > 0 && numUpDown_Dependentes.Value >= listbox_NomesDep.Items.Count)

Correct condition to allow the same counter value

if (numUpDown_Dependentes.Value > 0 && numUpDown_Dependentes.Value > listbox_NomesDep.Items.Count)

Another detail would be to prevent the user from decreasing the count without before removing an item from the list. the following code is an event ValueChanged of NumericUpDown

//Verifica se o valor do contador é menor que os itens da lista
private void numUpDown_Dependentes_ValueChanged(object sender, EventArgs e)
{
   var nud = sender as NumericUpDown;

   if(nud.Value < listbox_NomesDep.Items.Count)
   {
       MessageBox.Show("Você não pode diminuir a contagem sem antes remover um departamento cadastrado!");
       numUpDown_Dependentes.Value = listbox_NomesDep.Items.Count;
   }
}

And you can’t forget to also allow you to remove the item from the list and at the same time decrease the value of the counter. The following code is an event of MouseClick of ListBox

private void listbox_NomesDep_MouseClick(object sender, MouseEventArgs e)
{
    //seleciona o valor que o usuario clicou
    var selectedItem = listbox_NomesDep.SelectedItem;
    if(selectedItem != null)
    {
        //remove da lista
        listbox_NomesDep.Items.Remove(selectedItem);
        //diminui 1 do contador
        numUpDown_Dependentes.Value -= 1;
    }
}

I hope I’ve helped.

Browser other questions tagged

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