Cally K

Cally K

  • 1.2k
  • 507
  • 15.6k

Retain values of List between page postbacks

Jan 24 2019 2:14 AM
I am working on this code and I realised that the List gets initialized everytime from a different event handler. I do not want the List to be initialized to empty, I need the value to be retained. I have placed the declaration of the list in the class instead of in the method. Please go through my code and correct me. 
Hi, I have edited my post, did some reading and realised that it is very much connected to retaining values between page postbacks. 
  1. public partial class WebForm4 : System.Web.UI.Page  
  2.    {  
  3.        #region List of Weeks  
  4.        public List A_Week_1 = new List();  
  5.        public List A_Week_2 = new List();  
  6.        public List A_Week_3 = new List();  
  7.        public List A_Week_4 = new List();  
  8.        public List A_Week_5 = new List();  
  9.        public List A_Week_6 = new List();  
  10.        #endregion  
  11.   
  12.         
  13.          
  14.   
  15.   
  16.        protected void Page_Load(object sender, EventArgs e)  
  17.        {  
  18.             
  19.                  
  20.   
  21.        }  
  22.        protected void btnUpload_Click(object sender, EventArgs e)  
  23.        {  
  24.   
  25.            if (FileUpload1.HasFile)  
  26.            {  
  27.                try  
  28.                {  
  29.                    string filename = Path.GetFileName(FileUpload1.FileName);  
  30.                    //FileUpload1.SaveAs(Server.MapPath("~/Uploaded Files/") + filename);  
  31.                    string fileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName);  
  32.   
  33.                    string fileLocation = Server.MapPath("~/Uploaded Files/" + filename);  
  34.                    FileUpload1.SaveAs(fileLocation);  
  35.                    lblMessage.Text = "Upload status: File uploaded to " + fileLocation;  
  36.   
  37.                    readfile();  
  38.                }  
  39.                catch (Exception ex)  
  40.                {  
  41.                    lblMessage.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;  
  42.                }  
  43.            }  
  44.        }  
  45.        protected void readfile()  
  46.        {  
  47.            //datasource  
  48.            string connString = ConfigurationManager.ConnectionStrings["testexcel"].ConnectionString;  
  49.   
  50.            //object represents a unique connection to a data source.  
  51.            OleDbConnection oledbConn = new OleDbConnection(connString);  
  52.   
  53.            try  
  54.            {  
  55.                // Open connection  
  56.                oledbConn.Open();  
  57.                DataTable dtsheet = new DataTable("storesheettable");  
  58.                //because the oledbConn.GetOlddbSchemaTable returns datatale  
  59.                dtsheet = oledbConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);  
  60.   
  61.                //initialize and call constructor  
  62.                if (dtsheet == null)  
  63.                {  
  64.                    Label1.Text = "No sheet to display";  
  65.                }  
  66.                else  
  67.                {  
  68.   
  69.                    //String[] excelSheets = new String[dtsheet.Rows.Count];  
  70.                    List<string> import_excel_weeks_list = new List<string>();  
  71.                    //int i = 0;  
  72.   
  73.   
  74.                    char[] charsToTrim = { '$' };  
  75.                    for (int i = 0; i < dtsheet.Rows.Count; i++)  
  76.                    {  
  77.                        //excelSheets[i] = dtsheet.Rows.ToString();  
  78.                        import_excel_weeks_list.Add(dtsheet.Rows[i]["TABLE_NAME"].ToString().Trim(charsToTrim));  
  79.   
  80.                          
  81.                    }  
  82.   
  83.                    Repeater1.DataSource = import_excel_weeks_list;  
  84.                    Repeater1.DataBind();  
  85.                }  
  86.   
  87.   
  88.            }  
  89.            catch (Exception ex)  
  90.            {  
  91.                catchexception.Text = ex.ToString();  
  92.   
  93.            }  
  94.            finally  
  95.            {  
  96.                // Close connection  
  97.                oledbConn.Close();  
  98.            }  
  99.   
  100.        }  
  101.        protected void checkcalendarweek(string weekname)  
  102.        {  
  103.            if (weekname == "Week2")  
  104.            {  
  105.                int storemonth;  
  106.                DateTime today = new DateTime();  
  107.                storemonth = today.Month;  
  108.                Response.Write(storemonth);  
  109.                
  110.   
  111.            }  
  112.        }  
  113.        public void monthsddl_SelectedIndexChanged(object sender, EventArgs e)  
  114.        {  
  115.            int total_no_days;  
  116.            int selected_month = Convert.ToInt32(monthsddl.SelectedValue);  
  117.   
  118.            //total number of days in the month for the year  
  119.            total_no_days = DateTime.DaysInMonth(DateTime.Today.Year, selected_month);  
  120.            Label1.Text = String.Format("Total number of days in the month of {0} is {1}", monthsddl.SelectedItem,total_no_days);  
  121.   
  122.   
  123.            DateTime firstOfMonth = new DateTime(Convert.ToInt32(DateTime.Now.Year), selected_month, 1);  
  124.            int startdayofthemonth = (int)DayOfWeek.Monday;  
  125.            //total weeks in a month  
  126.            int weeksInMonth = (int)Math.Ceiling((startdayofthemonth + total_no_days) / 7.0);  
  127.   
  128.             
  129.   
  130.            int weeknum = 0;  
  131.   
  132.            //dates are of course from 1 to the total_no_days  
  133.            for (int i = 1; i <= total_no_days; i++)  
  134.            {  
  135.                //create the date based on the selected month with i starting as 1  
  136.                DateTime date1 = new DateTime(DateTime.Today.Year, selected_month, i);  
  137.                DateTime dateonly = date1.Date;  
  138.                //get the local culture timeformat  
  139.                DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;  
  140.   
  141.                //gets the calendar for the local timeformat and assign it to a type of calendar, gregorian  
  142.                System.Globalization.Calendar cal = dfi.Calendar;  
  143.                int num = cal.GetWeekOfYear(date1, dfi.CalendarWeekRule, (DayOfWeek.Monday));  
  144.   
  145.                //week in a month  
  146.                DateTime test = new DateTime(date1.Year, date1.Month, 1);  
  147.                int num2 = cal.GetWeekOfYear(test, dfi.CalendarWeekRule, (DayOfWeek.Monday));  
  148.                weeknum = num - num2 + 1;  
  149.   
  150.                //input dates for the week  
  151.                if (weeknum == 1)  
  152.                {  
  153.                    A_Week_1.Add(date1);  
  154.                }  
  155.                else if(weeknum == 2)  
  156.                {  
  157.                    //week2.Add(new Week() { datefortheweek = date1 });  
  158.                    A_Week_2.Add(date1);  
  159.                }  
  160.                else if(weeknum == 3)  
  161.                {  
  162.                    //week3.Add(new Week() { datefortheweek = date1 });  
  163.                    A_Week_3.Add(date1);  
  164.                }  
  165.                else if (weeknum == 4)  
  166.                {  
  167.                    //week4.Add(new Week() { datefortheweek = date1 });  
  168.                    A_Week_4.Add(date1);  
  169.                }  
  170.                else if (weeknum == 5)  
  171.                {  
  172.                    //week5.Add(new Week() { datefortheweek = date1 });  
  173.                    A_Week_5.Add(date1);  
  174.                }  
  175.                else  
  176.                {  
  177.                    //week6.Add(new Week() { datefortheweek = date1 });  
  178.                    A_Week_6.Add(date1);  
  179.                }  
  180.   
  181.   
  182.   
  183.                Response.Write(weeknum);  
  184.              
  185.   
  186.                Response.Write(" ");  
  187.                Response.Write(dateonly.ToString("dd/M/yyyy"));  
  188.                Response.Write(" ");  
  189.                Response.Write(dateonly.DayOfWeek);  
  190.                Response.Write("
    "
    );  
  191.   
  192.            }  
  193.   
  194.   
  195.              
  196.   
  197.            //displaying the list  
  198.            foreach (DateTime text in A_Week_5)  
  199.            {  
  200.                Response.Write(text);  
  201.                Response.Write("
    "
    );  
  202.            }  
  203.            //Response.Write("Test" + A_Week_5.Last().datefortheweek);  
  204.            Response.Write("Test" + A_Week_5.Last());  
  205.            //createtable(weeksInMonth, week1.First().datefortheweek, week1.Last().datefortheweek);  
  206.            createtable(weeknum, A_Week_1, A_Week_2, A_Week_3, A_Week_4, A_Week_5, A_Week_6);  
  207.        }  
  208.   
  209.        protected void createtable(int pass_in_weeksInMonth, List week_1, List week_2, List week_3, List week_4, List week_5, List week_6)  
  210.        {  
  211.              
  212.            DataTable createweek_dates = new DataTable();  
  213.            DataColumn column_createweek_dates;  
  214.            DataRow rows_createweek_dates;  
  215.   
  216.            //Column 1  
  217.            column_createweek_dates = new DataColumn();  
  218.            column_createweek_dates.DataType = Type.GetType("System.Int32");  
  219.            column_createweek_dates.ColumnName = "Week Number";  
  220.            column_createweek_dates.ReadOnly = true;  
  221.            column_createweek_dates.Unique = true;  
  222.            // Add the Column to the table  
  223.            createweek_dates.Columns.Add(column_createweek_dates);  
  224.   
  225.            //Column 2  
  226.            column_createweek_dates = new DataColumn();  
  227.            column_createweek_dates.DataType = Type.GetType("System.DateTime");  
  228.            column_createweek_dates.ColumnName = "Start Date";  
  229.            column_createweek_dates.ReadOnly = true;  
  230.            //column_createweek_dates.Unique = true;  
  231.            // Add the Column to the table  
  232.            createweek_dates.Columns.Add(column_createweek_dates);  
  233.   
  234.            //Column 3  
  235.            column_createweek_dates = new DataColumn();  
  236.            column_createweek_dates.DataType = Type.GetType("System.DateTime");  
  237.            column_createweek_dates.ColumnName = "End Date";  
  238.            column_createweek_dates.ReadOnly = true;  
  239.            //column_createweek_dates.Unique = true;  
  240.            // Add the Column to the table  
  241.            createweek_dates.Columns.Add(column_createweek_dates);  
  242.              
  243.            for (int i = 1; i <= pass_in_weeksInMonth; i++)  
  244.            {                
  245.                //new row for every creation  
  246.                rows_createweek_dates = createweek_dates.NewRow();  
  247.                rows_createweek_dates["Week Number"] = i;  
  248.                for (int j = i; j <= i; j++)  
  249.                {  
  250.                    if (j == 1)  
  251.                    {  
  252.                        rows_createweek_dates["Start Date"] = week_1.First();  
  253.                        rows_createweek_dates["End Date"] = week_1.Last();  
  254.                    }  
  255.                    else if (j == 2)  
  256.                    {  
  257.                        rows_createweek_dates["Start Date"] = week_2.First();  
  258.                        rows_createweek_dates["End Date"] = week_2.Last();  
  259.                    }  
  260.                    else if (j == 3)  
  261.                    {  
  262.                        rows_createweek_dates["Start Date"] = week_3.First();  
  263.                        rows_createweek_dates["End Date"] = week_3.Last();  
  264.                    }  
  265.                    else if (j == 4)  
  266.                    {  
  267.                        rows_createweek_dates["Start Date"] = week_4.First();  
  268.                        rows_createweek_dates["End Date"] = week_4.Last();  
  269.                    }  
  270.                    else if (j == 5)  
  271.                    {  
  272.                        rows_createweek_dates["Start Date"] = week_5.First();  
  273.                        rows_createweek_dates["End Date"] = week_5.Last();  
  274.                    }  
  275.                    else  
  276.                    {  
  277.                        rows_createweek_dates["Start Date"] = week_6.First();  
  278.                        rows_createweek_dates["End Date"] = week_6.Last();  
  279.                    }  
  280.   
  281.                }  
  282.               
  283.                createweek_dates.Rows.Add(rows_createweek_dates);  
  284.            }  
  285.   
  286.            rptItemsInCart.DataSource = createweek_dates;  
  287.            rptItemsInCart.DataBind();  
  288.   
  289.        }  
  290.        public void DoSend(object sender, EventArgs e)  
  291.        {  
  292.            AllLists create1 = new AllLists();  
  293.            for (int i = 0; i < rptItemsInCart.Items.Count; i++)  
  294.            {  
  295.                //Retrieve the state of the CheckBox  
  296.                CheckBox cb = (CheckBox)rptItemsInCart.Items[i].FindControl("CheckBox1");  
  297.                if (cb.Checked)  
  298.                {  
  299.                    //Retrieve the value associated with that CheckBox  
  300.                    HiddenField hiddentext = (HiddenField)rptItemsInCart.Items[i].FindControl("HiddenField1");  
  301.   
  302.                    //Now we can use that value to do whatever we want  
  303.                    Label2.Text = hiddentext.Value;  
  304.                    create1.user_select_weeks_list.Add(hiddentext.Value);  
  305.                }  
  306.            }  
  307.   
  308.            selected_weeks_repeater.DataSource = create1.user_select_weeks_list;  
  309.            selected_weeks_repeater.DataBind();  
  310.   
  311.            foreach(DateTime dates1 in A_Week_1)  
  312.            {  
  313.                Response.Write(dates1);  
  314.            }  
  315.             
  316.        }  
  317.        public void Week_button_Click(object sender, EventArgs e)  
  318.        {  
  319.            DataTable excel_data_gd = new DataTable();  
  320.            DataColumn edg_column;  
  321.            DataRow edg_row;  
  322.   
  323.            //get the data from repeater control  
  324.            AllLists create1 = new AllLists();  
  325.            for(int i = 0; i < selected_weeks_repeater.Items.Count; i++)  
  326.            {  
  327.                Label pass_as_label = (Label)selected_weeks_repeater.Items[i].FindControl("store_user_sheet");  
  328.                create1.user_select_weeks_list.Add(pass_as_label.Text);  
  329.            }  
  330.   
  331.            //for(int j = 0; j < create1.user_select_weeks_list.Count; j++)  
  332.            //{  
  333.            //    Response.Write(create1.user_select_weeks_list[j]);  
  334.            //}  
  335.   
  336.   
  337.            // Column1 - Machine Name  
  338.            edg_column = new DataColumn();  
  339.            edg_column.DataType = System.Type.GetType("System.String");  
  340.            edg_column.ColumnName = "Machine Name";  
  341.            edg_column.ReadOnly = true;  
  342.            edg_column.Unique = true;  
  343.            // Add the Column to the DataColumnCollection.  
  344.            excel_data_gd.Columns.Add(edg_column);  
  345.   
  346.            string[] machinename_array1 = Import_xml_file();  
  347.            for (int i = 0; i < machinename_array1.Length; i++)  
  348.            {  
  349.                edg_row = excel_data_gd.NewRow();  
  350.                edg_row["Machine Name"] = machinename_array1[i];  
  351.                //import from excel the value  
  352.                excel_data_gd.Rows.Add(edg_row);  
  353.            }  
  354.   
  355.            //check if the user has selected any value or not  
  356.            if(create1.user_select_weeks_list.Contains("Week2"))  
  357.            {  
  358.                //check got how many dates within the week  
  359.   
  360.                int count_of_dates = A_Week_2.Count;  
  361.                // The dates column, create a new column for every date within the week  
  362.               for(int i = 0; i < count_of_dates; i++)  
  363.                {   
  364.                    edg_column = new DataColumn();  
  365.                    edg_column.DataType = System.Type.GetType("System.DateTime");  
  366.                    edg_column.ColumnName = A_Week_2[i].ToString();  
  367.                    edg_column.ReadOnly = true;  
  368.                    edg_column.Unique = true;  
  369.                    // Add the Column to the DataColumnCollection.  
  370.                    excel_data_gd.Columns.Add(edg_column);  
  371.                }  
  372.            }  
  373.              
  374.   
  375.   
  376.   
  377.   
  378.   
  379.   
  380.            GridView1.DataSource = excel_data_gd;  
  381.            GridView1.DataBind();  
  382.   
  383.        }  
  384.        protected string[] Import_xml_file()  
  385.        {  
  386.            XmlDocument doc = new XmlDocument();  
  387.            doc.Load(Server.MapPath("~/App_Data/List_of_machines.xml"));  
  388.            //Display all the Activities alone in the XML    
  389.            XmlNodeList elemList = doc.GetElementsByTagName("machine_name");  
  390.   
  391.            string[] machinename_array = new string[elemList.Count];  
  392.            for (int i = 0; i < elemList.Count; i++)  
  393.            {  
  394.                machinename_array[i] = elemList[i].InnerXml;  
  395.            }  
  396.   
  397.            return machinename_array;  
  398.   
  399.   
  400.        }  
  401.    }  
  402.      
What is the best way of retaining the values, ViewState or Session, I read that viewstate if used with large data can cause the page to load slower, how can I go about solving this.
 
 

Answers (1)