I need your help with using one array to track 3 pieces of data. I have o use one array because it is school assignment and I am required to do so. The array has to track Province ID, Region ID and the population for each region. There is 13 province and in each province there is 48 regions. Since the array is fixed size, I used a 624 by 3 multi dimensional array. The first column is for the provinceID, the second is for the regionID, and the third one is for the population.. I set the rows to 624 because there is 13 province and 48 regions in each province so 13*48 = 624.
I was able to insert my data and display them like this
ProvinceID # 1 RegionID # 1: 125000
Instead I would like to display the regions and population by province.
Something like this:
ProvinceID #1
RegionID # 1: 12000
RegionID # 2: 30000
ProvinceID #2
RegionID #1: 14000
RegionID #: 145000
Here is what I did I declare a global array int[,] census;
I initialize it on form initialize census = new int[624,3];
Here is my insert
try
{
// declare variables
int prov, region, population;
prov = Convert.ToInt32(txtProvinceID.Text);
region = Convert.ToInt32(txtRegionID.Text);
population = Convert.ToInt32(txtPopulation.Text);
census[counter, 0] = prov;
census[counter, 1] = region;
census[counter, 2] = population;
counter++;
MessageBox.Show("Population " + txtPopulation.Text.ToString() + " saved for Province #" + txtProvinceID.Text.ToString()
+ " , Region #" + txtRegionID.Text.ToString(), "Success!");
txtRegionID.Clear();
txtProvinceID.Clear();
txtPopulation.Clear();
txtProvinceID.Focus();
}
catch (Exception ex)
{
if (ex.Message == "Input string was not in a correct format.")
{
MessageBox.Show("Please enter a numeric value", "Error");
}
else
{
MessageBox.Show(ex.Message, "Error");
}
}
This is the code to retrieve the data and save them to a file
string output = "";
try
{
for (int rows = 0; rows < census.GetLength(0); rows++)
{
for (int columns = 0; columns < census.GetLength(1); columns++)
{
if (census[rows, columns] != 0)
{
if (columns == 0)
{
output += "Province ID #" + census[rows, columns];
}
else if (columns == 1)
{
output += "Region ID #" + census[rows, columns] + ": ";
}
else if (columns == 2)
{
output += census[rows, columns] + "\n";
}
}// END if census[rows, coloumns]!=0
}// END for coloumns
}//END for(int row =0
// save the data to a text file
SaveFileDialog sfd = new SaveFileDialog();
sfd.FileName = "untitled";
sfd.Filter = "Text (*.txt)|*.txt|Word Doc (*.doc)|*.doc";
sfd.DefaultExt = "txt";
sfd.AddExtension = true;
sfd.ShowDialog();
FileStream sf = new FileStream(sfd.FileName, FileMode.Create);
StreamWriter sw = new StreamWriter(sf);
sw.Write(output);
sw.Close();
}
catch (Exception)
{
}