+92 332 4229 857 99ProjectIdeas@Gmail.com

Add , Delete and Update In ListBox (C#.net)




The following piece of code shows you how to add , delete and update in listbox.









public void clearTextBoxes()
{
     txtName.Clear();
     txtAge.Clear();
     txtDegree.Clear();
}

private void btnAdd_Click(object sender, EventArgs e)
{
     listName.Items.Add(txtName.Text);
     listAge.Items.Add(txtAge.Text);
     listDegree.Items.Add(txtDegree.Text);

     clearTextBoxes();   
}

// Deleting the selected row from all listboxes
private void btnDelete_Click(object sender, EventArgs e)
{
    int index = listName.SelectedIndex;
 
    listName.Items.RemoveAt(index);
    listAge.Items.RemoveAt(index);
    listDegree.Items.RemoveAt(index);

}

private void btnUpdate_Click(object sender, EventArgs e)
{
           
    if (btnUpdate.Text.Equals("Load"))
    {
         txtName.Text = listName.SelectedItem.ToString();
         txtAge.Text = listAge.SelectedItem.ToString();
         txtDegree.Text = listDegree.SelectedItem.ToString();
               
         listName.Enabled = false;
         listAge.Enabled = false;
         listDegree.Enabled = false;
  
         btnUpdate.Text = "Update";
               
   }
   else
   {
         int index = listName.SelectedIndex;
         listName.Items.Insert(index, txtName.Text);
         index++;
         listName.Items.RemoveAt(index);

         index = listAge.SelectedIndex;
         listAge.Items.Insert(index, txtAge.Text);
         index++;
         listAge.Items.RemoveAt(index);

         index = listDegree.SelectedIndex;
         listDegree.Items.Insert(index, txtDegree.Text);
         index++;
         listDegree.Items.RemoveAt(index);
               
         listName.Enabled = true;
         listAge.Enabled = true;
         listDegree.Enabled = true;
    
         btnUpdate.Text = "Load";
     }

}

// If click on listName then selecting its corresponding listbox row
private void listName_Click(object sender, EventArgs e)
{
       int index = listName.SelectedIndex;
       listAge.SelectedIndex = index;
       listDegree.SelectedIndex = index;
}

0 comments: