Home > Back-end >  add the newest added item to the lisbtox
add the newest added item to the lisbtox

Time:09-29

while working on an project i just can't seem to figure out how to add the newest added item to the lisbtox.

this is the code for adding a new article in the form (what i want to show in the list box after it is made):

 if (rbNormal.Checked)
 {
     articleManager.AddArticle(new NewsArticle(Convert.ToInt32(txtNewsNumber.Text), txtNewsTitle.Text, txtNewsText.Text, false));
     lbSeeNewsItem.Items.Clear();
 }

the code in articleManager:

 //Add article
 public void AddArticle(Article article)
 {
     items.Add(article);
 }

CodePudding user response:

You need some way to identify the last added article. As you control adding article via your ArticleManager, then you can do this here.

Add the following new property to ArticleManager class

public Article LastAddedArticle { get; private set; } = null;

Then change the adding method

public void AddArticle(Article article)
{
    LastAddedArticle = article;
    items.Add(article);
}

Then you just look in articleManager.LastAddedArticle to get the last one added. Bear in mind that this can be null, so you may need to check!

CodePudding user response:

If lbSeeNewsItem is your listbox, then you are just clearing it:

lbSeeNewsItem.Items.Clear();

If it's done on purpose, then just add your article like:

lbSeeNewsItem.Items.Add(article);

where article is the one NewsArticle just created. Important thing is that you have to override ToString() method in Article or NewsArticle to return the string that should be visible in ListBox. As ListBox reads its content from ToString() method. So for example:

class Article
{
   public string Title {get; set;}

   public override string ToString()
   {
        return Title;
   }
}
  •  Tags:  
  • c#
  • Related