Product serial number manipulation

Borresen77

New member
Joined
Jun 20, 2020
Messages
1
Programming Experience
Beginner
Good day all, I am working on a project and i am trying to find a way to manipulate a product serial number that is read from a combobox and written to a String which is then applied to a print of a Label. The Label media was changed and now the area is alot smaller so i need to reduce the serial number printed to 4 characters as apposed to 10. Here is an example, in the combobox you would select 1234A00123 all i want to be pulled from the serial number for this variable is A123, so the Alphabet and last 3 characters of the serial. Is there a specific way the cut this when it is being read into a string? this is the code used to pull the selected serial number. ( string text = comboBoxPartNumbers.SelectedItem.ToString(); ) Any advice is welcome.
 
Firstly, the items in the ComboBox already are strings so, while it's not strictly wrong, it's less appropriate to call ToString on them. That's generally to create a string from something that isn't. If the object is a string already but you're accessing it via an object reference then the more appropriate option is to cast:
C#:
var text = (string) comboBoxPartNumbers.SelectedItem;
That said, if what you want is the text displayed for the SelectedItem then you can just use the Text property, which is already type string:
C#:
var text = comboBoxPartNumbers.Text;
 
As for the question, does the letter appear in the same place in the text every time? If so then you could do this:
C#:
var text = comboBoxPartNumbers.Text;

text = text[4] + text.Substring(7, 3);
or this:
C#:
text = text.Substring(4, 1) + text.Substring(7, 3);
or other variations like that.
 
Assuming that you have the text using this:
C#:
var text = comboBoxPartNumbers.Text;

Then to get the first alphabetic character, you would do something like:
C#:
var firstAlphaChar = text.First(ch => Char.IsLetter(ch));
This invokes the LINQ extension method First() which will return the first character that satisfies the condition Char.IsLetter().

To get the last 3 "digits" of the text, we just get the last 3 characters of the text (taking advantage of C# 8.0's indexes and ranges):
C#:
var lastThreeChars = text[^3..];

Then we just put it all together:
C#:
var abbreviatedText = firstAlphaChar + lastThreeChars;

Here's a sample program:
C#:
using System;
using System.Linq;

namespace ConsoleApp8
{
    class Program
    {
        static void Main(string[] args)
        {
            var text = "1234A00123";

            var firstAlphaChar = text.First(ch => char.IsLetter(ch));
            var lastThreeChars = text[^3..];
            var abbreviatedText = firstAlphaChar + lastThreeChars;
            Console.WriteLine($"{abbreviatedText}");
        }
    }
}
 
Back
Top Bottom