locked
Giving variable individual name based on integer RRS feed

  • Question

  • User-718146471 posted

    I know I am doing this wrong, Visual keeps giving me red underlines. What I'm trying to do is declare a DateTime variable named MyDateTime[i]

    The integer i is going to be populated by incrementing by i and this way it increments by one each time it loops until the end of the record set. Any ideas?

                try
                {
                    var i = 0;
                    conn.Open();
                    SqlDataReader rdr2 = cmd2.ExecuteReader();
                    while (rdr2.Read())
                    {
                        DateTime MyDateTime[i] = Convert.ToDateTime(rdr2.GetValue(0).ToString());                    
                    }

    Wednesday, January 11, 2017 5:52 PM

Answers

  • User753101303 posted

    Hi,

    Beyond "red underlines" you do have a more explicit text message shown in the error list or when you are hovering the error. Here the problem is that you are mixing declaring an array and using a particular array cell. It's a bit hard to fix as usually an array is a good choice if you know in advance what is the array size you need. Here it might be more convenient to use a list ie something such as :

                    var MyDateTime = new List<DateTime>(); // needs using System.Collections.Generic;
                    while (rdr2.Read())
                    {
                        MyDateTime.Add(Convert.ToDateTime(rdr2.GetValue(0).ToString()));                    
                    }
    

    Not directly related but GetValue(0) returns a db value which is more likely ALREADY a datetime. If confirmed you could cast the value and use it directly rather than converting this value to a string and then back to a datetime ie try :

    MyDateTime.Add((DateTime)rdr2.GetValue(0));  

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, January 11, 2017 6:40 PM
  • User2103319870 posted

    AFAIK C# doesn't allow to create dynamic variables. IMO you should read the values to a list or array.

    Sample code using GetValues Method of SqlDataReader

     try
                {
                    int i = 0;
                    conn.Open();
                    SqlDataReader rdr2 = cmd2.ExecuteReader();
                    Object[] values = new Object[rdr2.FieldCount];
                    int fieldCount = rdr2.GetValues(values);
                    for (int j = 0; j < fieldCount; j++)
                    {
                        Console.WriteLine(values[i]);
                    }
                }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, January 11, 2017 6:43 PM
  • User-1716253493 posted

    The value conning from the database is an integer, I'm trying to make the datetime value be added to the name of the variable so i can loop through the values coming from the database.

    Not sure abaut your reauirement, elabore it.

    int x = //get it from db
    for (i=0;i<x;i++)
    {
      datelist.add(....);
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 12, 2017 12:33 AM
  • User-707554951 posted

    Hi  bbcompent1,

    For your problem, I suggest you could use Dictionary .

    Code as below:

    int i = 0;
                string sourcename = "MyDateTime";
                Dictionary<string, DateTime> d = new Dictionary<string, DateTime>(); 
                while (i < 5)
                {
                    string name=string.Format("MyDateTime{0}", i);
                    d[name] = DateTime.Now;
                    i++;
                }

    The data in d as below:

    Best Regards

    Cathy

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 12, 2017 9:14 AM
  • User-718146471 posted

    With everyone's advice, I got it working. Here's the code:

                string _csConnStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
                SqlConnection conn = new SqlConnection(_csConnStr);
                SqlConnection conn2 = new SqlConnection(_csConnStr);
                SqlDataAdapter da = new SqlDataAdapter();
                string query = "SELECT SchedID from TaskSchedule";
                SqlCommand cmd = new SqlCommand(query, conn);
                da.SelectCommand = cmd;
                DataSet selectResults = new DataSet();
    
                int RecID = 0;
                string TaskName = string.Empty, TaskDescr = string.Empty, TaskDay = string.Empty, TaskStartTime = string.Empty, TaskEndTime = string.Empty, CodeBase = string.Empty;
                bool Enabled = false, EmailOK = false;
                conn.Open();
                da.Fill(selectResults);
                conn.Close();
                foreach (DataTable table in selectResults.Tables)
                {
                    foreach (DataRow row in table.Rows)
                    {
                        foreach (object item in row.ItemArray)
                        {
                            RecID = Convert.ToInt32(item.ToString());
                            string query2 = "SELECT TaskName, TaskDescr, TaskDay, TaskStartTime, Enabled, EmailOK, CodeBase from TaskSchedule where SchedID = " + RecID + "";
                            SqlCommand cmd2 = new SqlCommand(query2, conn2);
                            try
                            {
                                conn2.Open();
                                SqlDataReader rdr2 = cmd2.ExecuteReader();
                                while (rdr2.Read())
                                {
                                    // Now walk through the scheduler stuff
    
                                    TaskName = rdr2.GetValue(0).ToString();
                                    TaskDescr = rdr2.GetValue(1).ToString();
                                    TaskDay = rdr2.GetValue(2).ToString();
                                    TaskStartTime = rdr2.GetValue(3).ToString();
                                    Enabled = Convert.ToBoolean(rdr2.GetValue(4));
                                    EmailOK = Convert.ToBoolean(rdr2.GetValue(5));
                                    CodeBase = rdr2.GetValue(6).ToString();
                                }
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("Error: " + ex.ToString());
                            }
                            finally
                            {
                                conn2.Close();
                            }
                        }
                    }
                }

    Thanks everyone for your guidance.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 12, 2017 1:43 PM
  • User2103319870 posted

    bbcompent1

    string query2 = "SELECT TaskName, TaskDescr, TaskDay, TaskStartTime, Enabled, EmailOK, CodeBase from TaskSchedule where SchedID = " + RecID + "";

    You might consider changing above line as your code is open for sql injection attach. You can use paramterized queries to resolve this issue.

    string _csConnStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
                SqlConnection conn = new SqlConnection(_csConnStr);
                SqlConnection conn2 = new SqlConnection(_csConnStr);
                SqlDataAdapter da = new SqlDataAdapter();
                string query = "SELECT SchedID from TaskSchedule";
                SqlCommand cmd = new SqlCommand(query, conn);
                da.SelectCommand = cmd;
                DataSet selectResults = new DataSet();
    
                int RecID = 0;
                string TaskName = string.Empty, TaskDescr = string.Empty, TaskDay = string.Empty, TaskStartTime = string.Empty, TaskEndTime = string.Empty, CodeBase = string.Empty;
                bool Enabled = false, EmailOK = false;
                conn.Open();
                da.Fill(selectResults);
                conn.Close();
                foreach (DataTable table in selectResults.Tables)
                {
                    foreach (DataRow row in table.Rows)
                    {
                        foreach (object item in row.ItemArray)
                        {
                            RecID = Convert.ToInt32(item.ToString());
                            string query2 = "SELECT TaskName, TaskDescr, TaskDay, TaskStartTime, Enabled, EmailOK, CodeBase from TaskSchedule where SchedID = @RecID";
                            SqlCommand cmd2 = new SqlCommand(query2, conn2);
                            // Add parameters to the command and pass the value.
                            cmd2.Parameters.Add("@RecID", SqlDbType.Int);
                            cmd2.Parameters["@RecID"].Value = RecID;
                            try
                            {
                                conn2.Open();
                                SqlDataReader rdr2 = cmd2.ExecuteReader();
                                while (rdr2.Read())
                                {
                                    // Now walk through the scheduler stuff
    
                                    TaskName = rdr2.GetValue(0).ToString();
                                    TaskDescr = rdr2.GetValue(1).ToString();
                                    TaskDay = rdr2.GetValue(2).ToString();
                                    TaskStartTime = rdr2.GetValue(3).ToString();
                                    Enabled = Convert.ToBoolean(rdr2.GetValue(4));
                                    EmailOK = Convert.ToBoolean(rdr2.GetValue(5));
                                    CodeBase = rdr2.GetValue(6).ToString();
                                }
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("Error: " + ex.ToString());
                            }
                            finally
                            {
                                conn2.Close();
                            }
                        }
                    }
                }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 12, 2017 2:05 PM

All replies

  • User753101303 posted

    Hi,

    Beyond "red underlines" you do have a more explicit text message shown in the error list or when you are hovering the error. Here the problem is that you are mixing declaring an array and using a particular array cell. It's a bit hard to fix as usually an array is a good choice if you know in advance what is the array size you need. Here it might be more convenient to use a list ie something such as :

                    var MyDateTime = new List<DateTime>(); // needs using System.Collections.Generic;
                    while (rdr2.Read())
                    {
                        MyDateTime.Add(Convert.ToDateTime(rdr2.GetValue(0).ToString()));                    
                    }
    

    Not directly related but GetValue(0) returns a db value which is more likely ALREADY a datetime. If confirmed you could cast the value and use it directly rather than converting this value to a string and then back to a datetime ie try :

    MyDateTime.Add((DateTime)rdr2.GetValue(0));  

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, January 11, 2017 6:40 PM
  • User2103319870 posted

    AFAIK C# doesn't allow to create dynamic variables. IMO you should read the values to a list or array.

    Sample code using GetValues Method of SqlDataReader

     try
                {
                    int i = 0;
                    conn.Open();
                    SqlDataReader rdr2 = cmd2.ExecuteReader();
                    Object[] values = new Object[rdr2.FieldCount];
                    int fieldCount = rdr2.GetValues(values);
                    for (int j = 0; j < fieldCount; j++)
                    {
                        Console.WriteLine(values[i]);
                    }
                }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, January 11, 2017 6:43 PM
  • User-718146471 posted
    The value conning from the database is an integer, I'm trying to make the datetime value be added to the name of the variable so i can loop through the values coming from the database.
    Wednesday, January 11, 2017 7:07 PM
  • User-1716253493 posted

    The value conning from the database is an integer, I'm trying to make the datetime value be added to the name of the variable so i can loop through the values coming from the database.

    Not sure abaut your reauirement, elabore it.

    int x = //get it from db
    for (i=0;i<x;i++)
    {
      datelist.add(....);
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 12, 2017 12:33 AM
  • User753101303 posted

    Humm your wording is really confusing. Which value are you talking about? The array size? If rdr2.GetValue(0) is an integer I don't see how it could work. Also "make the datetime value be added to the name of the variable" doesn't seems to make sense at all.

    Try maybe to use a list to start first with something that works. Once you have something that works then we could start to discuss how to change this so that it fit your needs ?
    If you really need an array you could use https://msdn.microsoft.com/en-us/library/x303t819(v=vs.110).aspx that is List<T>.ToArray after the code I suggested.

    If you are new to programming you may want to have a look at https://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx to see how arrays are working. You can"t create "variable names" programmatically as you go. But a variable can be a "collection" of single values (arrays, lists, dictionnary) rather than a single value so that you the process those values using loops etc...

    Thursday, January 12, 2017 1:38 AM
  • User-707554951 posted

    Hi  bbcompent1,

    For your problem, I suggest you could use Dictionary .

    Code as below:

    int i = 0;
                string sourcename = "MyDateTime";
                Dictionary<string, DateTime> d = new Dictionary<string, DateTime>(); 
                while (i < 5)
                {
                    string name=string.Format("MyDateTime{0}", i);
                    d[name] = DateTime.Now;
                    i++;
                }

    The data in d as below:

    Best Regards

    Cathy

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 12, 2017 9:14 AM
  • User-718146471 posted

    With everyone's advice, I got it working. Here's the code:

                string _csConnStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
                SqlConnection conn = new SqlConnection(_csConnStr);
                SqlConnection conn2 = new SqlConnection(_csConnStr);
                SqlDataAdapter da = new SqlDataAdapter();
                string query = "SELECT SchedID from TaskSchedule";
                SqlCommand cmd = new SqlCommand(query, conn);
                da.SelectCommand = cmd;
                DataSet selectResults = new DataSet();
    
                int RecID = 0;
                string TaskName = string.Empty, TaskDescr = string.Empty, TaskDay = string.Empty, TaskStartTime = string.Empty, TaskEndTime = string.Empty, CodeBase = string.Empty;
                bool Enabled = false, EmailOK = false;
                conn.Open();
                da.Fill(selectResults);
                conn.Close();
                foreach (DataTable table in selectResults.Tables)
                {
                    foreach (DataRow row in table.Rows)
                    {
                        foreach (object item in row.ItemArray)
                        {
                            RecID = Convert.ToInt32(item.ToString());
                            string query2 = "SELECT TaskName, TaskDescr, TaskDay, TaskStartTime, Enabled, EmailOK, CodeBase from TaskSchedule where SchedID = " + RecID + "";
                            SqlCommand cmd2 = new SqlCommand(query2, conn2);
                            try
                            {
                                conn2.Open();
                                SqlDataReader rdr2 = cmd2.ExecuteReader();
                                while (rdr2.Read())
                                {
                                    // Now walk through the scheduler stuff
    
                                    TaskName = rdr2.GetValue(0).ToString();
                                    TaskDescr = rdr2.GetValue(1).ToString();
                                    TaskDay = rdr2.GetValue(2).ToString();
                                    TaskStartTime = rdr2.GetValue(3).ToString();
                                    Enabled = Convert.ToBoolean(rdr2.GetValue(4));
                                    EmailOK = Convert.ToBoolean(rdr2.GetValue(5));
                                    CodeBase = rdr2.GetValue(6).ToString();
                                }
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("Error: " + ex.ToString());
                            }
                            finally
                            {
                                conn2.Close();
                            }
                        }
                    }
                }

    Thanks everyone for your guidance.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 12, 2017 1:43 PM
  • User2103319870 posted

    bbcompent1

    string query2 = "SELECT TaskName, TaskDescr, TaskDay, TaskStartTime, Enabled, EmailOK, CodeBase from TaskSchedule where SchedID = " + RecID + "";

    You might consider changing above line as your code is open for sql injection attach. You can use paramterized queries to resolve this issue.

    string _csConnStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
                SqlConnection conn = new SqlConnection(_csConnStr);
                SqlConnection conn2 = new SqlConnection(_csConnStr);
                SqlDataAdapter da = new SqlDataAdapter();
                string query = "SELECT SchedID from TaskSchedule";
                SqlCommand cmd = new SqlCommand(query, conn);
                da.SelectCommand = cmd;
                DataSet selectResults = new DataSet();
    
                int RecID = 0;
                string TaskName = string.Empty, TaskDescr = string.Empty, TaskDay = string.Empty, TaskStartTime = string.Empty, TaskEndTime = string.Empty, CodeBase = string.Empty;
                bool Enabled = false, EmailOK = false;
                conn.Open();
                da.Fill(selectResults);
                conn.Close();
                foreach (DataTable table in selectResults.Tables)
                {
                    foreach (DataRow row in table.Rows)
                    {
                        foreach (object item in row.ItemArray)
                        {
                            RecID = Convert.ToInt32(item.ToString());
                            string query2 = "SELECT TaskName, TaskDescr, TaskDay, TaskStartTime, Enabled, EmailOK, CodeBase from TaskSchedule where SchedID = @RecID";
                            SqlCommand cmd2 = new SqlCommand(query2, conn2);
                            // Add parameters to the command and pass the value.
                            cmd2.Parameters.Add("@RecID", SqlDbType.Int);
                            cmd2.Parameters["@RecID"].Value = RecID;
                            try
                            {
                                conn2.Open();
                                SqlDataReader rdr2 = cmd2.ExecuteReader();
                                while (rdr2.Read())
                                {
                                    // Now walk through the scheduler stuff
    
                                    TaskName = rdr2.GetValue(0).ToString();
                                    TaskDescr = rdr2.GetValue(1).ToString();
                                    TaskDay = rdr2.GetValue(2).ToString();
                                    TaskStartTime = rdr2.GetValue(3).ToString();
                                    Enabled = Convert.ToBoolean(rdr2.GetValue(4));
                                    EmailOK = Convert.ToBoolean(rdr2.GetValue(5));
                                    CodeBase = rdr2.GetValue(6).ToString();
                                }
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("Error: " + ex.ToString());
                            }
                            finally
                            {
                                conn2.Close();
                            }
                        }
                    }
                }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 12, 2017 2:05 PM
  • User-718146471 posted

    Already did thanks :) Again, that was just quick and dirty, the code now uses parameterized queries

    Thursday, January 12, 2017 8:43 PM