Link to home
Start Free TrialLog in
Avatar of zimmer9
zimmer9Flag for United States of America

asked on

How to reference a variable (variable does not exist in the current context) in a USING clause in C#?

I am developing a C# application in VS2010.

In the following code, how could I resolve the error:

Error      1      The name 'banknum' does not exist in the current context      \\msad\root\na\ny\users\zimmermj\visual studio 2010\Projects\SMRWebForm\SMRWebForm\SMRWebForm1.aspx.cs      71      29      SMRWebForm
-------------------------------------------

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace SMRWebForm
{
    public partial class SMRWebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            List<string> ReadFile = File.ReadAllLines(@"U:\SnrMgtRpt\OI_DRS.txt").ToList();

            foreach (string line in ReadFile)
            {                
                string banknum = line.Substring(0, 4);
                string transDtYR = line.Substring(4, 4);
                string transDtMnth = line.Substring(8, 2);                
            }

            const string myInsert = "INSERT INTO tbl_SMR_OI_WRS (bankNum, transYR, transMnth, transDay, clientAcct, transType, recordNum, recordNum, processYr) VALUES ('{0}', {1}, {2}, {3}, '{4}', '{5}', '{6}', {7}, '{8}')";
           
            const string connString = "Data Source=FSMSAPPSSQLDEV,7003;Initial Catalog=UDLPWM;User ID =UDLClient;PWD=Call_Me_UDLA;";

            using (SqlConnection conn = new SqlConnection(connString))
            {
                conn.Open();
                StringBuilder sb = new StringBuilder();
                string[] sArray = new string[9];
                sArray[0] = banknum;      <-------------------  error
                sArray[1] = transDtYR;
                sArray[2] = transDtMnth;
                sb.AppendFormat(myInsert, sArray);
                string cmdText = sb.ToString();
                using (SqlCommand cmd = new SqlCommand(connString))
                {
                   int rowsAffected = cmd.ExecuteNonQuery();
                }
            }
        }
    }
}
ASKER CERTIFIED SOLUTION
Avatar of AndyAinscow
AndyAinscow
Flag of Switzerland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Note that ignores all the lines until the last line in the file - because you loop through each line and then throw the values from the previous line away.  It is however the logic you have in your code snippet.  

(I suspect it is incorrect and you actually want to have the rest of the code inside that foreach loop.)