We help IT Professionals succeed at work.

assign string to an array in a loop adds to array not replaces in array

johnecollins
johnecollins asked
on
1,628 Views
Last Modified: 2012-05-05
I have a tab delimited file I am reading and want to store in a datatable
I use a stream to read in each line of the file an assign to string variable
Cleanse the data (replace commas with nothing, ' with `)
I then use this row to create an array
string[] s = szinString.Split(new char[] { '\t' });
First time through I get the 11 fields I need
s      {Length=11}      string[]
      [0]      "ESRX"      string
      [1]      "Express Scripts Inc"      string
      [2]      "64.97"      string
      [3]      "65.09"      string
      [4]      "63.88"      string
      [5]      "64.83"      string
      [6]      "5403"      string
      [7]      "0.47"            string
      [8]      "DIVERSIFIED SERVICES - Business/Management Services"      string
      [9]      "NASDAQ"      string
      [10]      "20071123"      string

Second time through I get 21 because element 1 of row 2 is merged with element 11 of row 1
s      {Length=21}      string[]
      [0]      "ESRX"      string
      [1]      "Express Scripts Inc"      string
      [2]      "64.97"      string
      [3]      "65.09"      string
      [4]      "63.88"      string
      [5]      "64.83"      string
      [6]      "5403"      string
      [7]      "0.47"      string
      [8]      "DIVERSIFIED SERVICES - Business/Management Services"      string
      [9]      "NASDAQ"      string
      [10]      "20071123ESRX"      string
      [11]      "Express Scripts Inc"      string
      [12]      "65.96"      string
      [13]      "66.29"      string
      [14]      "64.20"      string
      [15]      "64.36"      string
      [16]      "17183"      string
      [17]      "-1.34"      string
      [18]      "DIVERSIFIED SERVICES - Business/Management Services"      string
      [19]      "NASDAQ"      string
      [20]      "20071121"      string

Until line 2 I thought this was working marvelously but another exceotion fired and that was that

Thanks

John
Comment
Watch Question

Hi,

can you post a bit more code, and maybe a sample of the data (if possible). Also what exception is it that you are getting?

I'm guessing you want to read in one row at a time and that your code seems to be reading row 1 and 2 on the second pass?

Author

Commented:
Hi Babycorn-Starfish

This is the whole function

            private void ReadCreate(string fileName)
            {
                  string szreadString;
                  string szchosen;
                  string szlastTick;
                  string szcurrentTick;
                  string szoutString;
                  int istringLength;
                  int icounter;
                  int iRowCount;
                  int icolindex;

                  // initialise
                  szlastTick = "";
                  icolindex = 0;
                  szcurrentTick = "";
                  szDaily_DT = dtpSelectDate.Value.Year.ToString() + "-";
                  szDaily_DT += dtpSelectDate.Value.Month.ToString() + "-";
                  szDaily_DT += dtpSelectDate.Value.Day.ToString();

                  for (int i = 0; i < 50; i++)
                  {
                        if (szcbxTradeContents == szTradeDescription[i])
                        {
                              szTrade = szTradeShortCode[i];
                        }
                        if (szcbxSourceContents == szSourceDescription[i])
                        {
                              szSource = szSourceShortCode[i];
                        }
                  }
                  szExport = " ";
                  szRiskReward = " ";
                  try
                  {
                        StreamReader sr = new StreamReader(File.Open(@fileName, FileMode.Open));
                        icounter = 0;
                        szoutString = "";
                        DataTable dt = new DataTable();
                        dt.Columns.Add("Tick");
                        dt.Columns.Add("TickName");
                        dt.Columns.Add("Open");
                        dt.Columns.Add("High");
                        dt.Columns.Add("Low");
                        dt.Columns.Add("Close");
                        dt.Columns.Add("Volume");
                        dt.Columns.Add("Change");
                        dt.Columns.Add("Industry");
                        dt.Columns.Add("Exchange");
                        dt.Columns.Add("InfoDate");
                        
                        try
                        {
                              while  ((szreadString = sr.ReadLine())!=null)
                              {
                                    istringLength = szreadString.Length;
                                    while (icounter < istringLength)
                                    {
                                          szchosen = szreadString.Substring(icounter,1);
                                          switch (szchosen)
                                          {
                                                case ",":
                                                      szchosen = "";
                                                      break;
                                                case "\t":
                                                      szchosen = ",";
                                                      break;
                                                case "'":
                                                      szchosen = "`";
                                                      break;
                                                default:
                                                      break;
                                          }
                                          szoutString += szchosen;
                                          icounter += 1;
                                    }
                                    
                                    //String[] s = new szoutString.Split(char[]'/t');
                                    String[] items ;
                                    char[] delim = {','};
                                    items = szoutString.Split(delim);
                                    dt.Rows.Add(items);
                                    

                        for (int i = 0; i < 11; i++)
                                    {
                                          items[i] = "";
                                    }
                                    icounter = 0;
                              }
                        }
                        finally
                        {
                              sr.Close();
                        }
                        int rowCount = dt.Rows.Count;
                        DataRow dr;
                        for (int indexrow = 0; indexrow < rowCount; indexrow++)
                        {
                              dr = dt.Rows[indexrow];
                              // work with the content
                              // get the fields
                              szTick = dr["Tick"].ToString();
                              szTickName = dr["TickName"].ToString();
                              szOpen = dr["Open"].ToString();
                              szHigh = dr["High"].ToString();
                              szLow = dr["Low"].ToString();
                              szClose = dr["Close"].ToString();
                              szVolume = dr["Volume"].ToString();
                              szChange = dr["Change"].ToString();
                              szExchange = dr["Exchange"].ToString();
                              szIndustry = dr["Industry"].ToString();
                              szPrice_DT = dr["InfoDate"].ToString();
                        }
                  }
                  catch (Exception Exc)
                  {
                        MessageBox.Show(Exc.Message);
                  }
            }

filename is passed into the function
datatable dt created and fields allocated
while reading through the file it singles out:-
1 commas and replaces these with nothing
2 tabs and replaces them with commas, identifying field terminator
3 ' because that's a SQL field delimiter and replaces them with`
At the end of the line I am assigning the string I create to an array
items = szoutString.Split(delim);
even though I initialise the array before assigning as in line above on the second time through it rediscovers items 0 to 10 and merges what I want to be item 0 the second time with item 10 the first time and and makes an array of 21 elelments
datatable dt has 11 fields and the next line is the catch line:-
MessageBox.Show(Exc.Message);
but this doesn't produce the 'normal' instead it porduces
a messagebox that says
"Input array is longer than the number of columns in this table"
and an Ok button
I saw this solution on EE andthought how neat it was but have been thwarted every time
I have thought a little more and as I know when a  field is terminated I can assign the contents to a explicit array element as I work through
It has been extremely helpful to me to review and comment on my code if you can help I will still be very grateful - I am not sure that my new thoughts will work
So thanks for your time and attention
John
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Commented:
Closed, 500 points refunded.
Vee_Mod
Community Support Moderator

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.