none
How do I solve Index was outside the bounds of array RRS feed

  • Question

  • How do I solve Index was outside the bounds of array? Where exactly the error is coming from? How do I fix it? 

    Much appreciate for your help.

    namespace 
    {
        public partial class : UserControl
        {   
     _foundationWs = tProxyProperties.Proxy();
            DataTable dtWAF = null;
    
            EnrolmentIntendedCourse[] _intendedCourse = null;
            EnrolmentIntendedCourse[] _intendedCourseList = null;
            //NormalisedCompositeScoreSetup[] _WeightageList = null;
            NormalisedCompositeScoreSetup[] _WeightageList;
    
            //NormalisedCompositeScoreSpecialFactorSetup[] _specialFactorData = null;
            NormalisedCompositeScoreSpecialFactorSetup[] _specialFactorData;
    
            NormalisedCompositeScoreSpecialFactorSetup[] _existingSpecialFactor = null;
            NormalisedCompositeScoreSetup[] _compositeScoreSetup = null;
            
            //added for PopulateWeightage and Special Factor
            NormalisedCompositeScoreSpecialFactorSetup[] _setupList = null;
    
            readonly bool _isViewMode;
    
            string _useinName= string.Empty;
            string _calledFrom= string.Empty;
    
            string _selectedUseInCourse;
            int _selectedIntendedCourse;
    
    
            DateRange[] _studyPeriods;
            DateRange studyPeriod= null;
            int _courseTypeId;
                    
            RegisteredCourse[] _selectedCourse;
            int _courseType = 0;
    
            NormalisedCompositeScoreSetup _newNCSData = new NormalisedCompositeScoreSetup();
            List<NormalisedCompositeScoreSpecialFactorSetup> _newNCSSpecialFactorData = null;
    
            //NormalisedCompositeScoreSetup _compositeData;
            List<NormalisedCompositeScoreSpecialFactorSetup> _compositeDataSpecialFactor;
    
            NormalisedCompositeScoreSetup[] compositeSetup = null;
            //NormalisedCompositeScoreSpecialFactorSetup[] existingSpecialFactor = null;
    
            //for GetWeightageAndSpecialFactorSetupRecordsForEditingPage
            DataSet _setupRecords2 = null;
            int RegisterdCourseId = 0;
    
            int _registerdCourseId = 0;
            string _coursename;
            string _studyPeriodDate;
            public int _intendedCourseId = -1;
            string _courseName;
    
            //CopyTo
            string _selectedCopyToCourse;
            string _selectedCopyToStudyPeriod;
    
            public WeighAndSpecialFactorForFoundation(int _registerdCourseId, string _courseName, string _studyPeriodDate, int _intendedCourseId)
            {
                InitializeComponent();
                this._registerdCourseId = _registerdCourseId;
                this._courseName = _courseName;
                this._studyPeriodDate = _studyPeriodDate;
                this._intendedCourseId = _intendedCourseId;
    
                lblCourse.Text = _courseName;
                lblStudyPeriod.Text = _studyPeriodDate;
    
    
                if (_isViewMode)
                {
                    BtnSave.Enabled = false;
                    btnCancel.Enabled = false;
                    panel1.Enabled = false;
                }
    
                _calledFrom = "Load";
                if (initialBackground.IsBusy == false)
                    initialBackground.RunWorkerAsync();
            }
    
    
          
    
            private void populateUseInCourse()
            {
                // Prevent the automatic execution of SelectedIndexChanged event while loading the combo box
                cboUseIn.SelectedIndexChanged -= cboUseIn_SelectedIndexChanged;
                cboUseIn.ValueMember = "useInSystemModuleName";
                cboUseIn.ValueMember = "IsShow";
                cboUseIn.DataSource = _intendedCourse;
                cboUseIn.SelectedIndex = -1;
                cboUseIn.SelectedIndexChanged += cboUseIn_SelectedIndexChanged;
            }
    
            private void populateIntendedCourse()
            {
                //Prevent the automatic execution of SelectedIndexChanged event while loading the combo box
                cboIntendedCourse.SelectedIndexChanged -= cboIntendedCourse_SelectedIndexChanged;
                DataTable dtCourse = new DataTable();
    
                dtCourse.Columns.Add("Id", typeof(int));
                dtCourse.Columns.Add("Name", typeof(string));
                foreach (EnrolmentIntendedCourse course in _intendedCourseList)
                {
                    //dtCourse.Rows.Add(course.EnrolmentIntendedCourseId, string.Format("{0}({1})", course.IntendedCourseName, course.CourseCode));
                    dtCourse.Rows.Add(course.IntendedCourseId, string.Format("{0}({1})", course.IntendedCourseName, course.CourseCode));
                }
                cboIntendedCourse.DisplayMember = "Name";
                cboIntendedCourse.ValueMember = "Id";
                cboIntendedCourse.DataSource = dtCourse;
                cboIntendedCourse.SelectedIndex = -1;
                cboIntendedCourse.SelectedIndexChanged += cboIntendedCourse_SelectedIndexChanged;
            }
    
            //populating Weightage and Special Factor
            private void populateWeightage()
            {
                DataTable dt2 = new DataTable();
                dt2.Columns.Add("Registered_course_id", typeof(int));
                dt2.Columns.Add("SpecialFactor", typeof(string));
                dt2.Columns.Add("SpecialFactorDescription", typeof(string));
                dt2.Columns.Add("weighting_educational_qualification", typeof(decimal));
                dt2.Columns.Add("weighting_admission_test", typeof(decimal));
    
    
                for (int i = 0; i < _setupList.Length; i++)
                {
                    dt2.Rows.Add(
                        _setupRecords2.Tables[0].Rows[i]["Registered_course_id"], _setupRecords2.Tables[0].Rows[i]["SpecialFactor"],
                        _setupRecords2.Tables[0].Rows[i]["SpecialFactorDescription"],
                        _setupRecords2.Tables[0].Rows[0]["weighting_educational_qualification"],
                        _setupRecords2.Tables[0].Rows[i]["weighting_admission_test"]
                               );
               }
    
            }
    
            private void populateResultGrid()
            {
                dtWAF = new DataTable();
                dtWAF.Columns.Add("NCSSpecialFactorSetupFoundationID", typeof(int));
                dtWAF.Columns.Add("SpecialFactor", typeof(decimal));
                dtWAF.Columns.Add("Description", typeof(string));
                if (_specialFactorData != null)
                {
                    for (int i = 0; i < _specialFactorData.Length; i++)
                    {
    
                        dtWAF.Rows.Add(_specialFactorData[i].NormalisedCompositeScoreSpecialFactorSetupFoundationID,
                            _specialFactorData[i].SpecialFactor, _specialFactorData[i].SpecialFactorDescription);
                    }
                }
    
                DataGridViewTextBoxColumn colView;
                colView = new DataGridViewTextBoxColumn();
                colView.DataPropertyName = "NCSSpecialFactorSetupFoundationID";
                colView.ValueType = typeof(int);
                colView.Name = colView.DataPropertyName;
                colView.HeaderText = "NCS Special Factor Setup FoundationID";
                colView.Visible = false;
                resultGrid.Columns.Add(colView);
    
                colView = new DataGridViewTextBoxColumn();
                colView.DataPropertyName = "SpecialFactor";
                colView.ValueType = typeof(decimal);
                colView.Name = colView.DataPropertyName;
                colView.HeaderText = "Special Factor";
                colView.MaxInputLength = 4;
                colView.Visible = true;
                resultGrid.Columns.Add(colView);
    
                colView = new DataGridViewTextBoxColumn();
                colView.DataPropertyName = "Description";
                colView.ValueType = typeof(string);
                colView.Name = colView.DataPropertyName;
                colView.HeaderText = "Description";
                colView.MaxInputLength = 50;
                colView.Visible = true;
                resultGrid.Columns.Add(colView);
    
                resultGrid.DataSource = dtWAF;
    
            }
            
            private void PopulateStudyPeriod()
            {
    
                cboStudyPeriod.SelectedIndexChanged -= cboStudyPeriod_SelectedIndexChanged;
    
                DataTable studyPeriodDT = new DataTable();
                studyPeriodDT.Columns.Add("StudyPeriod", typeof(string));
    
                if (_studyPeriods != null)
                {
                    for (int i = 0; i < _studyPeriods.Length; i++)
                    {
                        studyPeriodDT.Rows.Add(
                        _studyPeriods[i].StartDate.ToString("dd/MM/yy hh:mm:ss tt") + " - " + _studyPeriods[i].EndDate.ToString("dd/MM/yy hh:mm:ss tt"));
    
                    }
                }
    
                cboStudyPeriod.DataSource = studyPeriodDT;
                cboStudyPeriod.DisplayMember = "StudyPeriod";
                cboStudyPeriod.SelectedIndexChanged += cboStudyPeriod_SelectedIndexChanged;
    
            }
            //populateCourse
            private void PopulateCourse()
            {
                
                //Prevent the automatic execution of SelectedIndexChanged event while loading the combo box
                cboCopyToCourse.SelectedIndexChanged -= cboCopyToCourse_SelectedIndexChanged;
                DataTable dtCourseCopyTo = new DataTable();
    
                dtCourseCopyTo.Columns.Add("Id", typeof(int));
                dtCourseCopyTo.Columns.Add("Name", typeof(string));
                foreach (EnrolmentIntendedCourse course in _intendedCourseList)
                {
                    dtCourseCopyTo.Rows.Add(course.IntendedCourseId, string.Format("{0}", course.IntendedCourseName));
                }
                cboCopyToCourse.DisplayMember = "Name";
                cboCopyToCourse.ValueMember = "Id";
                cboCopyToCourse.DataSource = dtCourseCopyTo;
                cboCopyToCourse.SelectedIndex = -1;
                cboCopyToCourse.SelectedIndexChanged += cboCopyToCourse_SelectedIndexChanged;
    
            }
    
    
            private void CheckingOnSaving()
            {
                try
                {
                    if (ValidationForCalculation() == false)
                    {
                        MessageBox.Show("Data is saved successfully", "Weightage And Special Factor", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        txtWAT.Focus();
                        return;
                    }
                    else
                    {
                        MessageBox.Show("You have not made any chages.", "Weightage And Special Factor", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        txtWAT.Focus();
                        return;
                    }
                }
                catch(Exception e)
                {
                    MessageBox.Show(e.Message.ToString(), "Weightage And Special Factor", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
    
            private bool ValidationForCalculation()
            {
                bool flag = false;
                if (txtWAT.Text != string.Empty && txtWEQ.Text != string.Empty)
                {
                    decimal total = decimal.Parse(txtWAT.Text) + decimal.Parse(txtWEQ.Text);
                    if (total == 1)
                        flag = true;
                    else
                        flag = false;
                }
                return flag;
            }
    
            private bool SavingCheckChange()
            {
                bool flag = false;
    
                _newNCSSpecialFactorData = new List<NormalisedCompositeScoreSpecialFactorSetup>();
    
    
                for (int i = 0; i < resultGrid.Rows.Count; i++)
                {
                    if (Convert.ToInt32(resultGrid.Rows[i].Cells["NCSSpecialFactorSetupFoundationID"].Value) == -1)
                    {
    
                        //NormalisedCompositeScoreSpecialFactorSetup specialFactor = new NormalisedCompositeScoreSpecialFactorSetup();
                        //specialFactor.NormalisedCompositeScoreSpecialFactorSetupFoundationID = Convert.ToInt32(resultGrid.Rows[i].Cells["NCSSpecialFactorSetupFoundationID"].Value);
                        //specialFactor.EnrolmentIntendedCourse = new Course();
                        //specialFactor.EnrolmentIntendedCourse. = Convert.ToInt32(resultGrid.Rows[i].Cells["CourseId"].Value);
                        flag = true;
                        NormalisedCompositeScoreSpecialFactorSetup specialFactor = new NormalisedCompositeScoreSpecialFactorSetup();
                        specialFactor.NormalisedCompositeScoreSpecialFactorSetupFoundationID = Convert.ToInt32(resultGrid.Rows[i].Cells["NCSSpecialFactorSetupFoundationID"].Value);
                        specialFactor.EnrolmentIntendedCourse = new Course();
                        specialFactor.EnrolmentIntendedCourse.CourseID= Convert.ToInt32(resultGrid.Rows[i].Cells["CourseId"].Value);
    
    
                        _newNCSSpecialFactorData.Add(specialFactor);
                    }
    
                    else
                    {
                        if (resultGrid.Rows[i].Cells["CourseId"].Value.ToString() != resultGrid.Rows[i].Cells["OldNCSSpecialFactorSetupFoundationID"].Value.ToString() ||
                            resultGrid.Rows[i].Cells["CutOffPoint"].Value.ToString() != resultGrid.Rows[i].Cells["OldNCSSpecialFactorSetupFoundationID"].Value.ToString())
                        {
                            flag = true;
                            NormalisedCompositeScoreSpecialFactorSetup specialFactor = new NormalisedCompositeScoreSpecialFactorSetup();
                            specialFactor.NormalisedCompositeScoreSpecialFactorSetupFoundationID = Convert.ToInt32(resultGrid.Rows[i].Cells["NCSSpecialFactorSetupFoundationID"].Value);
                            specialFactor.EnrolmentIntendedCourse = new Course();
                            specialFactor.EnrolmentIntendedCourse.CourseID = Convert.ToInt32(resultGrid.Rows[i].Cells["CourseId"].Value);
    
    
                            _newNCSSpecialFactorData.Add(specialFactor);
                        }
                    }
                }
    
                return flag;
            }
    
            private void RefreshGrid()
            {
                //_compositeScoreSetup = null;
                resultGrid.DataSource = null;
                txtWEQ.Text = "";
                txtWAT.Text = "";
                if (initialBackground.IsBusy == false)
                    initialBackground.RunWorkerAsync();
            }
    
            private bool DuplicateRecords()
            {
                bool flag = false;
    
                for (int x = 0; x < resultGrid.RowCount - 1; x++)
                {
    
                    DataRow[] dr = dtWAF.Select("SpecialFactor = '" + decimal.Parse(resultGrid.Rows[x].Cells["SpecialFactor"].Value.ToString())
                                                            + "' OR Description = '" + resultGrid.Rows[x].Cells["Description"].Value.ToString() + "' ");
                    if (dr.Length > 1)
                    {
                        flag = false;
                        break;
                    }
                    else
                    {
                        flag = true;
                        
                    }
                    
                }
    
                return flag;
    
            }
    
    #region BackGroundWorker
    
            private void initialBackground_DoWork(object sender, DoWorkEventArgs e)
            {
                try
                {
                    initialBackground.ReportProgress(0);
                    if (_calledFrom == "Load")
                    {
                        _intendedCourse = _foundationWs.GetAllEnrollmentIntendedCourse();
                    }
    
                    //else if (_calledFrom == "PopulateUseInCourse")
                    else if (_calledFrom == "populateUseInCourse")
                    {
                        _intendedCourseList = _foundationWs.GetAllEnrollmentIntendedCourseByUseInModuleName(_selectedUseInCourse);
                    }
                    else if (_calledFrom == "populateWeightage")
                    {
                        //_WeightageList = _foundationWs.GetAllNCSByCourseId(_intendedCourseId);
                        //_specialFactorData = _foundationWs.GetAllNCSSpecialFactorByCourseId(_intendedCourseId);
    
                        _WeightageList = _foundationWs.GetAllNCSByCourseId(_selectedIntendedCourse);
                        _specialFactorData = _foundationWs.GetAllNCSSpecialFactorByCourseId(_selectedIntendedCourse);
    
    
                        ////_setupRecords2 = _foundationWs.GetWeightageAndSpecialFactorSetupRecordsForEditingPage(RegisterdCourseId);
                    }
                    else if (_calledFrom == "Save")
                    {
                        _foundationWs.SaveNormalisedCompositeSpecialFactorList(_newNCSData, _newNCSSpecialFactorData.ToArray());
                    }
                    else if (_calledFrom == "PopulateStudyPeriod")
                    {
                        _studyPeriods = _foundationWs.GetStudyPeriods(_courseTypeId);
                    }
                    //else if (_calledFrom == "PopulateStudyPeriodForCopyTo")
                    //{
                    //    //_studyPeriods = _foundationWs.GetStudyPeriods(_courseTypeId);
                    //    _foundationWs.SaveNormalisedCompositeSpecialFactorList(_newNCSData, _newNCSSpecialFactorData.ToArray());
                    //}
                    else if (_calledFrom == "PopulateStudyPeriodForCopyTo")
                    {
                       string[] dates = _selectedCopyToStudyPeriod.Split('-');
                        
                        string StartDate = dates[0].Trim();
                        string EndDate = dates[1].Trim();
    
                        //
                        StartDate = Convert.ToString(studyPeriod.StartDate);
                        EndDate = Convert.ToString(studyPeriod.EndDate);
                        
                        _selectedCourse = _foundationWs.GetRegisteredCoursesByCourseType(studyPeriod, _courseType, AuthenticatedUser.UserSingleton.GetSingletonObject().userID);
                        
                     }
    
                    initialBackground.ReportProgress(100);
                }
                catch (Exception ex)
                {
                    e.Cancel = true;
                    ExceptionMessageBox.Show(ex);
                }
            }
    
            private void initialBackground_ProgressChanged(object sender, ProgressChangedEventArgs e)
            {
    
                if (e.ProgressPercentage < 100)
                    ShowWaitingBar(true);
                else
                    ShowWaitingBar(false);
            }
    
            private void initialBackground_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
            {
                try
                {
    
                    if (e.Error != null)
                    {
                        MessageBox.Show(e.Error.Message);
                    }
                    else if (e.Cancelled)
                    {
                        // Next, handle the case where the user canceled the operation.
                        // Note that due to a race condition in the DoWork event handler, the Cancelled flag may not have been set, even though CancelAsync was called.
                        ShowWaitingBar(false);
                    }
                    else
                    {
                        if (_calledFrom == "Load")
                        {
                            populateUseInCourse();
                            //populateIntendedCourse();
                        }
                        //else if (_calledFrom == "PopulateUseInCourse")
                        else if (_calledFrom == "populateUseInCourse")
                        {
                            populateIntendedCourse();
                        }
    
                        else if (_calledFrom == "populateWeightage")
                        {
                            populateResultGrid();
    
                            if (_WeightageList != null)
                            {
                                //_WeightageList.ToString();
                                //txtWEQ.Text = _WeightageList.WeightingEducationalQualification.ToString();
                                //txtWAT.Text = _WeightageList.WeightingEducationalAdmissionTest.ToString();
                                txtWEQ.Text = _WeightageList[0].WeightingEducationalQualification.ToString();
                                txtWAT.Text = _WeightageList[0].WeightingEducationalAdmissionTest.ToString();
                            }
                            else
                            {
                                txtWEQ.Text = "";
                                txtWAT.Text = "";
                            }
    
                            //populateResultGrid();
    
                        }
    
                        else if (_calledFrom == "populateStudyPeriod")
                        {
    
                            PopulateStudyPeriod();
                        }
    
                        //else if (_calledFrom == "Save")
                        //{
                        //    MessageBox.Show("Record is saved successfully.", "Weightage And Special Factor", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        //    RefreshGrid();
                        //}
                    }
    
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Unable to load" + "\n" + ex.Message, "Weightage And Special Factor", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
            }
    
    #endregion
    
            private void BtnSave_Click(object sender, EventArgs e)
            {
                try
                {
                    if (txtWAT.Text.ToString() == string.Empty)
                    {
                        MessageBox.Show("Please enter Weighing Of Admission Test/Audition.", "Weightage And Special Factor", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        txtWAT.Focus();
                        return;
                    }
    
                    if (txtWEQ.Text.ToString() == string.Empty)
                    {
                        MessageBox.Show("Please enter Weighing of Educational Qualification.", "Weightage And Special Factor", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        txtWEQ.Focus();
                        return;
                    }
                    if (resultGrid.RowCount == 1)
                    {
                        return;
                    }
                    else
                    {
                        string strMsg = string.Empty;
    
    
                       strMsg = ValidationForGridView();
                       if (strMsg != string.Empty)
                       {
                           MessageBox.Show( strMsg, "Weightage And Special Factor", MessageBoxButtons.OK, MessageBoxIcon.Error);
                           return;
                       }
                    }
                    if (DuplicateRecords() == false)
                    {
                        MessageBox.Show("Cannot update, duplicate records found. Please check Special Factor and Description.", "Weightage And Special Factor", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
    
                    }
                    if (decimal.Parse(txtWEQ.Text.Trim()) > 1)
                    {
                        MessageBox.Show("Weighing of Educational Qualification of maximum value is 1.", "Weightage And Special Factor", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        txtWEQ.Focus();
                        return;
                    }
                    if (decimal.Parse(txtWAT.Text.Trim()) > 1)
                    {
                        MessageBox.Show("Weighing of Admission Test of maximum value is 1.", "Weightage And Special Factor", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        txtWAT.Focus();
                        return;
                    }
                    if (ValidationForCalculation() == false)
                    {
                        MessageBox.Show("The Sum of Weighing of Educational Qualification and Weighing Of Admission Test/Audition should be equal 1.", "Weightage And Special Factor", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        txtWAT.Focus();
                        return;
                    }
                   
                        //new value stored from textboxes are assigned to new variables
                        _newNCSData.WeightingEducationalQualification = Convert.ToDecimal(txtWEQ.Text);
                        _newNCSData.WeightingEducationalAdmissionTest = Convert.ToDecimal(txtWAT.Text);
    
    
                        _newNCSData.CreatedBy = new User();
                        _newNCSData.CreatedBy.UserId = AuthenticatedUser.UserSingleton.GetSingletonObject().userID;
    
                        //new value stored from gridview
                        if (resultGrid.RowCount > 0)
                        {
                            _newNCSSpecialFactorData= new List<NormalisedCompositeScoreSpecialFactorSetup>();
                            
                            for (int i = 0; i < resultGrid.Rows.Count-1; ++i)
    
    
                            {
                                NormalisedCompositeScoreSpecialFactorSetup specialFactorSetUp = new NormalisedCompositeScoreSpecialFactorSetup();
    
                                if (resultGrid.Rows[i].Cells["NCSSpecialFactorSetupFoundationID"].Value.ToString() != string.Empty)
                                {
                                    specialFactorSetUp.NormalisedCompositeScoreSpecialFactorSetupFoundationID = int.Parse(resultGrid.Rows[i].Cells["NCSSpecialFactorSetupFoundationID"].Value.ToString());
                                }
    
                                //specialFactorSetUp.NormalisedCompositeScoreSpecialFactorSetupFoundationID = Convert.ToInt32(resultGrid["NCSSpecialFactorSetupFoundationID", i].Value);
                                specialFactorSetUp.SpecialFactor = Convert.ToDecimal(resultGrid["SpecialFactor", i].Value);
                                specialFactorSetUp.SpecialFactorDescription = Convert.ToString(resultGrid["Description", i].Value);
                                specialFactorSetUp.CreatedBy = new User();
                                specialFactorSetUp.CreatedBy.UserId = AuthenticatedUser.UserSingleton.GetSingletonObject().userID;
    
                                
                                    _newNCSSpecialFactorData.Add(specialFactorSetUp);    
                                
                            
                            }
                            _calledFrom = "Save";
    
                            MessageBox.Show("Record is save successfully.", "Weightage And Special Factor", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            RefreshGrid();
                        }
    
                   
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message.ToString(), "Weightage And Special Factor", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
    
    
            }
    
            private void btnCopy_Click(object sender, EventArgs e)
            {
                _calledFrom = "PopulateStudyPeriod";
    
                using (BackgroundWorker worker = new BackgroundWorker())
                {
                    if (worker.IsBusy == false)
                        worker.RunWorkerAsync();
                }
    
                PopulateStudyPeriod();
                
                _calledFrom = "PopulateStudyPeriodForCopyTo";
                using (BackgroundWorker worker = new BackgroundWorker())
                {
                    if (worker.IsBusy == false)
                        worker.RunWorkerAsync();
                }
                PopulateCourse();
    
            }
    
    
            private void btnCancel_Click(object sender, EventArgs e)
            {
                Form form = FindForm();
                if (form == null)
                    return; 
    
                //RemovePane("WeighAndSpecialFactorPane");
                RemovePane("WeightageAndSpecialFactorPane");
    
            }
    
            private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
            {
                Common.UserRight right = UserRightsCache.GetRights("Weigh and Special Factor", _useinName);
                if (!right.IsDelete)
                {
                    MessageBox.Show("You don't have sufficient rights to perform this operation.", "Weightage And Special Factor", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
    
    
                DialogResult result = MessageBox.Show("Are you sure you want to delete?", "Weightage And Special Factor", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    int rowcount = resultGrid.SelectedRows.Count;                               
                   
                    
                    foreach (DataGridViewRow drRow in resultGrid.SelectedRows)
                    {
                        if (!drRow.IsNewRow)
                        {
                            //setupWS.DeleteNormalisedCompositeScoreSpecialFactorSetup(int.Parse(drRow.Cells["SpecialFactorID"].Value.ToString()),
                            //_regID, AuthenticatedUser.UserSingleton.GetSingletonObject().userID);
                            //resultGrid.Rows.Remove(drRow);
                        }
                    }
                    if (resultGrid.RowCount == 1)
                    {
                        RefreshGrid();
                    }
                   
                }
                
            }
    
            private void txtWAT_KeyPress(object sender, KeyPressEventArgs e)
            {
    
                txtWAT.MaxLength = 4;
    
    
                if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
                {
                    e.Handled = true;
                }
                // only allow one decimal point
                if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
                {
                    e.Handled = true;
                }
                
            }
    
            private void txtWAT_TextChanged(object sender, EventArgs e)
            {
                string strWAT = string.Empty;
                if (txtWAT.Text.StartsWith("."))
                {
                    strWAT = "0" + txtWAT.Text.Trim();
    
                }
                else
                {
                    strWAT = txtWAT.Text.Trim();
                }
    
                if (txtWAT.Text != string.Empty)
                {
                    if (!txtWAT.Text.StartsWith(".") && decimal.Parse(txtWAT.Text.Trim()) > 1)
                    {
                        MessageBox.Show("Weighing of Admission Test of maximum value is 1.", "Weightage And Special Factor", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        txtWAT.Focus();
                        return;
                    }
                    else
                    {
                        decimal total = 1 - decimal.Parse(strWAT);
                        txtWEQ.Text = total.ToString();
                        txtWAT.Text = strWAT;
                        txtWAT.Select(txtWAT.TextLength, 0);
                    }
                }
                
            }
    
            private void txtWEQ_TextChanged(object sender, EventArgs e)
            {
    
    
                if (txtWEQ.Text != string.Empty)
                {
                    string strWEQ = string.Empty;
                    if (txtWEQ.Text.StartsWith("."))
                    {
                        strWEQ = "0" + txtWEQ.Text.Trim();
    
                    }
                    else
                    {
                        strWEQ = txtWEQ.Text.Trim();
                    }
    
                    if (!txtWEQ.Text.StartsWith(".") && decimal.Parse(txtWEQ.Text.Trim()) > 1)
                    {
                        MessageBox.Show("Weighing of Educational Qualification of maximum value is 1.", "Weightage And Special Factor", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        txtWEQ.Focus();
                        return;
                    }
                    else
                    {
                        decimal total = 1 - decimal.Parse(strWEQ);
                        txtWAT.Text = total.ToString();
                        txtWEQ.Text = strWEQ;
                        txtWEQ.Select(txtWEQ.TextLength, 0);
                    }
                }
            }
    
            private void txtWEQ_KeyPress(object sender, KeyPressEventArgs e)
            {
    
                txtWEQ.MaxLength = 4;
    
                if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
                {
                    e.Handled = true;
                }
                 ////only allow one decimal point
                if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
                {
                    e.Handled = true;
                }
                
            }
    
            private void resultGrid_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
            {
    
                if (this.resultGrid.CurrentCell.ColumnIndex == resultGrid.Columns["SpecialFactor"].Index)  //this is our numeric column    
                {
                    TextBox tx = e.Control as TextBox;
    
                    tx.KeyPress += new KeyPressEventHandler(tx_KeyPress);
                }
                           
            }
    
            private void resultGrid_RowLeave(object sender, DataGridViewCellEventArgs e)
            {
                if (resultGrid.Rows.Count > 1)
                {
    
                    deleteToolStripMenuItem.Visible = true;
                }
                else
                {
                    deleteToolStripMenuItem.Visible = false;
                }
            }
    
            private void resultGrid_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
            {
                if (resultGrid.Rows.Count > 1)
                {
    
                    deleteToolStripMenuItem.Visible = true;
                }
                else
                {
                    deleteToolStripMenuItem.Visible = false;
                }
            }
    
            #endregion
            #region Method
       
    
            private void tx_KeyPress(object sender, KeyPressEventArgs e)
            {
    
                if (this.resultGrid.CurrentCell.ColumnIndex == resultGrid.Columns["SpecialFactor"].Index) //this is our numeric column    
                    {
                       
                        if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
                        {
                            e.Handled = true;
                        }
                        //// only allow one decimal point
                        if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
                        {
                            e.Handled = true;
                        } 
                    }            
            }
    
            private bool ValidDecimal(char x, string Text)
            {
    
                string valid = "1234567890.";
                if (DecimalConvert(Text) == 0)
                {
                    Text = "";
                }
    
                if (valid.IndexOf(x) != -1)
                {
                    if (Text.Length == 0 && x == 0)
                        return false;
    
                    return true;
                }
    
                return false;
            }
    
    
    
            private string ValidationForGridView()
            {
                string Msg = string.Empty;
                if (resultGrid.RowCount > 1)
                {
                    for (int i = 0; i < resultGrid.RowCount - 1; i++)
                    {
                        if(resultGrid.Rows[i].Cells["SpecialFactor"].Value.ToString() == string.Empty)
                        {
                            Msg = "Please enter Special Factor.";
                            break;
    
                           }
                        else if (resultGrid.Rows[i].Cells["Description"].Value.ToString() == string.Empty)
                        {
                           Msg = "Please enter Description.";
                           break;
                        }
                    }
                }
                return Msg;
            }
    
            public double DecimalConvert(string text)
            {
                if (text.Length == 0)
                    return 0;
                else
                    return (Convert.ToDouble(text));
            }
    
    
    
    
    
    #region event
            public void cboUseIn_SelectedIndexChanged(object sender, EventArgs e)
            {
                try
                {
                    if (cboUseIn.SelectedIndex != -1)
                    {
                        _selectedUseInCourse = cboUseIn.Text;
                        _calledFrom = "populateUseInCourse";
                        //_calledFrom = "populateIntendedCourse";
    
                        if( cboUseIn.SelectedValue.ToString() == "Yes")
                        {
                            grpCopy.Enabled = true;
                        }
                        else
                        {
                            grpCopy.Enabled = false;
                        }
    
                        if (initialBackground.IsBusy == false)
                            initialBackground.RunWorkerAsync();
                    }
    
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Please select a Course", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
            }
    
            private void cboIntendedCourse_SelectedIndexChanged(object sender, EventArgs e)
            {
                try
                {
                    if (cboIntendedCourse.SelectedIndex != -1)
                    {
                        _selectedIntendedCourse = Convert.ToInt32(cboIntendedCourse.SelectedValue);
                        _calledFrom = "populateWeightage";
    
    
    
    
    
                        if (initialBackground.IsBusy == false)
                            initialBackground.RunWorkerAsync();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Please select an Intended Course", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
            }
    
            private void cboCopyToCourse_SelectedIndexChanged(object sender, EventArgs e)
            {
                try
                {
                    if (cboCopyToCourse.SelectedIndex != -1)
    
                    _selectedCopyToCourse = cboCopyToCourse.Text;
                    
                    _calledFrom = "PopulateCourseForCopyTo";
                    if (initialBackground.IsBusy == false)
                        initialBackground.RunWorkerAsync();
                    }
                
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Please select a Course to copy", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
            }
    
            private void cboStudyPeriod_SelectedIndexChanged(object sender, EventArgs e)
            {
                try
                {
                    if (cboStudyPeriod.SelectedIndex != 1)
    
                        _selectedCopyToStudyPeriod = cboStudyPeriod.Text;
    
                    _calledFrom = "PopulateStudyPeriodForCopyTo";
                    if (initialBackground.IsBusy == false)
                        initialBackground.RunWorkerAsync();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Please select a study period to copy", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
            }
    #endregion
    
    
    
        }
    }
    

    Thursday, November 15, 2018 1:34 PM

All replies

  • The secret is to use an index NOT out of bound...

    Eg: new array[10] means array[0] to array[9]...

    Thursday, November 15, 2018 2:12 PM
  • You're getting a message box so that tells you where. It is occurring in your BtnSave_Click method. Set a breakpoint at the start of that function and then execute it normally. When the breakpoint is hit start stepping through your code. Since you know it is an array index issue pay careful attention to the code that is referencing array-like structures. At some point while stepping you'll trigger an exception. The line you just executed was the cause.

    Additionally, since you have a try-catch around this code, when you're in the catch block you have access to the exception information via the variable you declared. The exception will tell you what went wrong (Message), where it went wrong (StackTrace) and what type of error occurred (Type). You can use all this to diagnose the problem without the need for stepping through the code, if necessary.


    Michael Taylor http://www.michaeltaylorp3.net

    Thursday, November 15, 2018 2:53 PM
    Moderator
  • It came out like that this morning. I was trying out as suggested. I think the error is coming out from this area of code, as it is the grid showing back after save. I found one mistake in writing array column. But I was still having Index out of bound error.         

           private void populateWeightage() {
                DataTable dt2 = new DataTable();
                dt2.Columns.Add("Registered_course_id", typeof(int));
                dt2.Columns.Add("SpecialFactor", typeof(string));
                dt2.Columns.Add("SpecialFactorDescription", typeof(string));
                dt2.Columns.Add("weighting_educational_qualification", typeof(decimal));
                dt2.Columns.Add("weighting_admission_test", typeof(decimal));
    
    
                for (int i = 0; i < _setupList.Length; i++)
                {
                    dt2.Rows.Add(
                        _setupRecords2.Tables[0].Rows[i]["Registered_course_id"], _setupRecords2.Tables[0].Rows[i]["SpecialFactor"],
                        _setupRecords2.Tables[0].Rows[i]["SpecialFactorDescription"],
                        _setupRecords2.Tables[0].Rows[i]["weighting_educational_qualification"],
                        _setupRecords2.Tables[0].Rows[i]["weighting_admission_test"]
                               );
               }
    
            }

    Friday, November 16, 2018 1:45 AM

  • You need to learn to use the debugger. Step through the loop in your last post line by line, checking the value of i and the Count of  _setupRecords2.Tables[0].Rows as you go and you will probably be able to spot what's wrong. Most likely _setupList has too many entries for  _setupRecords2.Tables[0].Rows to hold, probably because one or the other hasn't been initialised properly. I, for one, am not going to read those hundreds of lines of code to work out exactly why.
    Friday, November 16, 2018 2:02 AM
  • Step through the code to identify what is wrong. Given your code I think your for loop is suspect. You are enumerating through _setupList but you are referencing _setupRecords2. For this to be accurate _setupList.Length would need to be equal to the # of rows in Tables[0] of _setupRecords2. That seems really suspect to me. If you want to add each row from that able to your new DataTable then just enumerate the rows directly.

    foreach (DataRow row in _setupRecords2.Tables[0].Rows)
    {
       dt2.Rows.Add(row["Registered_course_id"], ...);
    };
    


    Michael Taylor http://www.michaeltaylorp3.net

    Friday, November 16, 2018 3:15 AM
    Moderator