dcsimg
 

Working with the Periodic Table and .NET

Thursday Jul 19th 2018 by Hannes DuPreez

Learn to write a program, in C# or VB.NET, to identify chemical elements on the Periodic table through the use of LINQ and the element's atomic number.

Introduction

Only very smart people would be able to tell you what each chemical element on the periodic table is, and to which group, period, and block each chemical element belongs; but, doing it through .NET is actually quite easy. Today, you will learn to write a program that can identify each chemical element on the Periodic table through the use of LINQ and the chemical element's atomic number.

The Periodic Table

The periodic table is a tabular arrangement of the chemical elements. These elements are ordered by their atomic number, electron configuration, and recurring chemical properties. The table consists of rows (period) and columns (groups). In each period, metals are to the left, and non-metals to the right, with the elements having similar chemical behaviors placed in the same column See Figure 1.

The Periodic Table
Figure 1: The Periodic Table
Picture Source: https://commons.wikimedia.org/wiki/File:Periodic_Table_Of_Elements_2016.jpg

Groups

A group or family is a column of chemical elements in the periodic table. Elements within the same group or family usually have the same electron configurations, have a shared chemistry, and exhibit a clear trend in properties with increasing atomic number. There are 18 numbered groups in the periodic table:

  1. Lithium
  2. Beryllium
  3. Scandium
  4. Titanium
  5. Vanadium
  6. Chromium
  7. Manganese
  8. Iron
  9. Cobalt
  10. Nickel
  11. Copper
  12. Zinc
  13. Boron
  14. Carbon
  15. Nitrogen
  16. Oxygen
  17. Fluorine
  18. Helium or Neon

Metals, Metalloids, and Nonmetals

Elements can be classified into the major categories of metals, metalloids, and nonmetals, according to their shared chemical and physical properties. Metals are shiny, highly conducting solids that can form alloys with one another, and salt-like ionic compounds with nonmetals.

Most nonmetals are colored or colorless insulating gases. In between metals and nonmetals are metalloids. Metalloids have intermediate or mixed properties.

The periodic table shows the graduation from metallic to non-metallic from left to right—highly reactive alkali metals, less reactive alkaline earth metals, lanthanides and actinides, transition metals, and chemically weak post-transition metals.

Periods

A horizontal row in the periodic table is known as a period. All elements in a period have the same number of electron shells. Each next element in a period then has one more proton and is less metallic than the previous element.

Blocks

Specific sections of the periodic table are known as blocks. This is in recognition of the sequence in which the electron shells of the chemical elements are filled. Each of these blocks is named according to the subshell in which the last electron resides.

Atomic Number

The atomic number (proton number) of a chemical element is the number of protons found in the nucleus (small, dense region consisting of protons and neutrons at the center of an atom) of an atom (smallest constituent unit of ordinary matter that has the properties of a chemical element). This number is identical to the charge number of the nucleus. The atomic number uniquely identifies each chemical element.

Proton

A proton is a subatomic particle (a particle is much smaller than an atom) with a positive electric charge of +1e elementary charge and mass slightly less than that of a neutron.

Neutron

The neutron is a subatomic particle with no net electric charge and a mass slightly larger than that of a proton.

Enough science! For now.

Our Project

The project that you will be creating today allows you to search the periodic table via the use of the element's atomic number to see what element it is as well as to which metal group (no, not Metallica or Iron Maiden! Although they rock) the element belongs to.

Before you even start with the project, create a text file and add all the necessary information in comma separated format. For example:

1,H,Hydrogen,Reactive nonmetal

2,He,Helium,Noble gas

3,Li,Lithium,Alkali metal

4,Be,Beryllium,Alkaline earth metal

5,B,Boron,Metalloid

114,Fl,Flerovium,Unknown

115,Mc,Moscovium,Unknown

116,Lv,Livermorium,Unknown

117,Ts,Tennessine,Unknown

118,Og,Oganesson,Unknown

Continue with all 118 elements. Save the file as PeriodicElements.txt. You will make use of this file in your program.

Design

Open Visual Studio and create either a C# or Visual Basic.NET Windows Forms application. Design your form so that it resembles Figure 2, and, as always, keep in mind that my object naming may be different than yours.

Design
Figure 2: Design

Add the PeriodicEelemnts.txt file that you created earlier to your project as a Resource. Do this by clicking Project->Project name Properties->Resources. Make sure you select File as a Resource Type and then select Existing File. Browse to your PeriodicElements.txt file and then it is added. Figure 3 shows what your screen should look like after you have added the file.

Project Resources
Figure 3: Project Resources

Code

Add a class named PeriodicElementType and add the following code into it.

C#

   class PeriodicElementType
   {
      private string name;

      public string Name()
      {

         return name;

      }

      public PeriodicElementType(string itemname)
      {

         name = itemname;

      }
   }

VB.NET

Public Class PeriodicElementType

   Private sname As String

   Public Function Name() As String

      Return sname

   End Function

   Public Sub New(ByVal itemname As String)

      sname = itemname

   End Sub

End Class

The PeriodicElementType class simply returns the name of the associated Group. You will make use of this class in the next class. Add a class named PeriodicElementDetails and add the following code into it.

C#

   class PeriodicElementDetails
   {
      private int atomicnumber;
      private string symbol;
      private string element;

      private PeriodicElementType type;

      public int AtomicNumber()
      {

         return atomicnumber;

      }

      public string Symbol()
      {

         return symbol;

      }

      public string Element()
      {

         return element;

      }

      public PeriodicElementType Group()
      {

         return type;

      }


      public PeriodicElementDetails(PeriodicElementType[]
         PelementTypes, string[] elements)
      {

         atomicnumber = Convert.ToInt32(elements[0].Trim());
         symbol = elements[1].Trim();
         element = elements[2].Trim();
         type = PelementTypes.Where(x => elements[3].Trim()
            .Equals(x.Name())).First();

      }
   }

VB.NET

Public Class PeriodicElementDetails

   Private iatomicnumber As Integer
   Private ssymbol As String
   Private selement As String
   Private ttype As PeriodicElementType

   Public Function AtomicNumber() As Integer

      Return iatomicnumber

   End Function

   Public Function Symbol() As String

      Return ssymbol

   End Function

   Public Function Element() As String

      Return selement

   End Function

   Public Function Group() As PeriodicElementType

      Return ttype

   End Function

   Public Sub New(ByVal PelementTypes As PeriodicElementType(), _
         ByVal elements As String())

      iatomicnumber = Convert.ToInt32(elements(0).Trim())
      sSymbol = elements(1).Trim()
      sElement = elements(2).Trim()
      ttype = PelementTypes.Where(Function(x) elements(3).Trim() _
         .Equals(x.Name())).First()

   End Sub

End Class

The PeriodicElementDetails class exposes all the chemical element's properties needed for the Periodic Table, as well as a call to the PeriodicEelementType class. In the constructor, each part gets entered into its associated property and the element's group gets stored via the help of a LINQ query that looks for all elements containing the specific metal group (again, no, it is not Pantera or Dio either!).

Inside the form, create a PeriodicElementType array to host the metal groups:

  • Alkali metal
  • Alkaline earth metal
  • Lanthanide
  • Actinide
  • Transition metal
  • Post-transition metal
  • Metalloid
  • Reactive nonmetal
  • Noble gas
  • Unknown

C#

      PeriodicElementType[] PeriodicElementTypes = {
         PeriodicElementType("Alkali metal"),
         new PeriodicElementType("Alkaline earth metal"),
         new PeriodicElementType("Lanthanide"),
         new PeriodicElementType("Actinide"),
         new PeriodicElementType("Transition metal"),
         new PeriodicElementType("Post-transition metal"),
         new PeriodicElementType("Metalloid"),
         new PeriodicElementType("Reactive nonmetal"),
         new PeriodicElementType("Noble gas"),
         new PeriodicElementType("Unknown") };

      PeriodicElementDetails[] PeriodicElements = new
         PeriodicElementDetails[118];

      int iPeriodicNumber = 0;

VB.NET

   Private PeriodicElementTypes As PeriodicElementType() = {
      New PeriodicElementType("Alkali metal"),
      New PeriodicElementType("Alkaline earth metal"),
      New PeriodicElementType("Lanthanide"),
      New PeriodicElementType("Actinide"),
      New PeriodicElementType("Transition metal"),
      New PeriodicElementType("Post-transition metal"),
      New PeriodicElementType("Metalloid"),
      New PeriodicElementType("Reactive nonmetal"),
      New PeriodicElementType("Noble gas"),
      New PeriodicElementType("Unknown")}

   Private PeriodicElements As PeriodicElementDetails() = New _
      PeriodicElementDetails(117) {}
   Private iPeriodicNumber As Integer = 0
   Private PeriodicElements As PeriodicElementDetails() = New _
      PeriodicElementDetails(117) {}
   Private iPeriodicNumber As Integer = 0

You also instantiated the PeriodicElements array to hold the 118 elements. For the uninformed: arrays start at 0 and not 1. That is why the array only has 117 elements.

Add the constructor that reads the PeriodicElements.txt file and stores the contents inside the PeriodicElements array:

C#

      public frmPeriodicInfo()
      {
         InitializeComponent();

         string[] peElements = Properties.Resources
            .PeriodicElements.Split(new string[]
            { Environment.NewLine }, StringSplitOptions.None);

         for (int x = 0; x <= 117; x++)
         {

            PeriodicElements[x] = new PeriodicElementDetails
               (PeriodicElementTypes, peElements[x].Split(','));

         }

      }

VB.NET

   Public Sub New()

      InitializeComponent()

      Dim peElements As String() = My.Resources.PeriodicElements _
         .Split(New String() {Environment.NewLine}, _
         StringSplitOptions.None)

      For x As Integer = 0 To 117

         PeriodicElements(x) = New PeriodicElementDetails _
            (PeriodicElementTypes, peElements(x).Split(","c))

      Next

   End Sub

Add the following sub procedure:

C#

      private void ShowInfo(PeriodicElementDetails CurrElement)
      {

         if (CurrElement != null)
         {

            txtSymbol.Text = CurrElement.Symbol();
            txtElement.Text = CurrElement.Element();
            txtGroup.Text = CurrElement.Group().Name();

            PeriodicElementDetails[] ElementGroup =
               PeriodicElements.Where(el => el.Group().Name()
               .Equals(txtGroup.Text)).ToArray();

            lstGroup.Items.Clear();

            foreach (PeriodicElementDetails eg in ElementGroup)
            {

               lstGroup.Items.Add(eg.AtomicNumber().ToString() +
                  ' ' + eg.Symbol().ToString() + ' ' +
                  eg.Element().ToString());

            }
         }


      }

VB.NET

   Private Sub ShowInfo(ByVal CurrElement As _
         PeriodicElementDetails)

      If CurrElement IsNot Nothing Then

         txtSymbol.Text = CurrElement.Symbol()
         txtElement.Text = CurrElement.Element()
         txtGroup.Text = CurrElement.Group().Name()

         Dim ElementGroup As PeriodicElementDetails() = _
            PeriodicElements.Where(Function(el) el.Group().Name() _
            .Equals(txtGroup.Text)).ToArray()

         lstGroup.Items.Clear()

         For Each eg As PeriodicElementDetails In ElementGroup

            lstGroup.Items.Add(eg.AtomicNumber().ToString() + _
               " "c + eg.Symbol().ToString() + " "c + _
               eg.Element().ToString())

         Next
      End If

   End Sub

The ShowInfo sub procedure extracts each associated part and places it inside the TextBoxes. Then, a For Each Loop is used to read all the elements belonging to the current group and adds them into the ListBox.

Add the plus and minus button events.

C#

      private void btnPlus_Click(object sender, EventArgs e)
      {

         iPeriodicNumber++;

         if (iPeriodicNumber >= 118)
         {

            iPeriodicNumber = 118;

         }

         txtPNumber.Text = iPeriodicNumber.ToString();

         ShowInfo(PeriodicElements.FirstOrDefault(el =>
            el.AtomicNumber() == iPeriodicNumber));

      }

      private void btnMinus_Click(object sender, EventArgs e)
      {

         iPeriodicNumber--;

         if (iPeriodicNumber <= 0)
         {

            iPeriodicNumber = 0;

         }

         txtPNumber.Text = iPeriodicNumber.ToString();

         ShowInfo(PeriodicElements.FirstOrDefault(el =>
            el.AtomicNumber() == iPeriodicNumber));

      }

VB.NET

   Private Sub btnPlus_Click_1(sender As Object, e As EventArgs) _
         Handles btnPlus.Click

      iPeriodicNumber += 1

      If iPeriodicNumber >= 118 Then

         iPeriodicNumber = 118

      End If

      txtPNumber.Text = iPeriodicNumber.ToString()
      ShowInfo(PeriodicElements.FirstOrDefault(Function(el) _
         el.AtomicNumber() = iPeriodicNumber))

   End Sub

   Private Sub btnMinus_Click_1(sender As Object, e As EventArgs) _
         Handles btnMinus.Click

      iPeriodicNumber -= 1

      If iPeriodicNumber <= 0 Then

         iPeriodicNumber = 0
      End If

      txtPNumber.Text = iPeriodicNumber.ToString()
      ShowInfo(PeriodicElements.FirstOrDefault(Function(el) _
         el.AtomicNumber() = iPeriodicNumber))

   End Sub

The plus button increments the iPeriodicNumber counter and calls the ShowInfo sub while passing the counter to it. The minus button does the same apart from decrementing the iPeriodicNumber counter.

Once run, your application will look similar to Figure 4.

Running
Figure 4: Running

The picture shows the details for the atomic number 3. The symbol is Li for Lithium. The Element Name is Lithium. It belongs to the Alkali metal group. The Alkali metal group contains Lithium, Sodium, Potassium, Rubidium, Cesium (Caesium in the picture is the British spelling), and Francium.

Code for this article is available on GitHub:

C#

VB.NET

Conclusion

Today's topic was very interesting, on a personal level. There is just so much to learn! I hope you have learned a great deal today and that you will put your knowledge to good use. Happy coding!

Home
Mobile Site | Full Site