简体   繁体   中英

C# Add value to combo box with identifier number

I am currently developing a program in C# that contains a combo box and a button to add a new item to the combo box when said button is pressed. I need it so that when the button is pressed and the item is added, it gradually builds up a list of items that have a number that increases by one for each item.

For example when the button has been pressed twice, the combo box will contain the following two items:

New Profile 1

New Profile 2

Etc.

I am making it so that the items are set to "New Profile" with the number by default so that the end-user isn't confused as to which profile is which but the user can change the items name later if they wish to, but I am struggling making this concept work in code.

I had the generic code to add a item to my combo box:

private void AddProfileButton_Click(object sender, EventArgs e)
{
    ProfileList.Items.Add("New Profile");
}

So, I tried drafting some code to see if I could accomplish my ideas on my own. This is my code:

        int a = 0;
        var b = a + 1;
        var NewProfileName = "New Profile " + b;
        ProfileList.Items.Add(NewProfileName);

However; when I tried this when the form was running, I kept getting items with the same name of "New Profile 1" repeatedly. So it sort of works - just that it doesn't increase the integer how I want it to.

I think part of the problem is the:

   int a = 0;

part of the code however my attempt(s) to fix this (pasting this line of code under the Form_Load event) have been a failure/inconclusive.

I would greatly appreciate someone's help and all suggestions are welcome.

Josh

Thanks to @LarsTech for the answer.

The code is:

ProfileList.Items.Add(string.Format("New Profile {0}", ProfileList.Items.Count + 1));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM