none
Object Reference not set to an object error at BtnSave_Click and cannot save to db RRS feed

  • Question

  • Hi,

    I am trying to save user input data into a database. All of my data saving method are coming from WebService. I have assigned and initialized the data values to be ready to save in Webservice. But I am always getting 'Null' to most of them and that is the main issue: that I cannot save into database and getting 'object reference not set to an instance'error at the end of BtnSave method. I am wondering those data becomes Null because I initialized that become override my returned data ? If not, I am getting Object Reference not set error for those individual fields. I've searched online why Null Error occurs, because we haven't initialized variable. But, in my case I am not sure what is happening. Maybe I have initialized them, and returned data cannot be passed into? 

    I have 2 sps for this BtnSave method, 1st one has 6 parameters-@enrolmentIntendedCourseId,@intendedCourseId,@weightingEducationalQualification,@weightingAdmissionTest,@status and @created By. 2nd one also have 6 parameters-@enrolmentIntendedCourseId,@intendedCourseId,@specialFactor,@Description,@status and @createdBy.

    _newNCSData.WeightingEducationalQualification = Convert.ToDecimal(txtWEQ.Text); _newNCSData.WeightingEducationalAdmissionTest = Convert.ToDecimal(txtWAT.Text); _newNCSData.Status="Active"; _newNCSData.IntendedCourse = new Course(); _newNCSData.IntendedCourse.CourseID = _registerdCourseId; _newNCSData.EnrolmentIntendedCourse = new Course(); _newNCSData.EnrolmentIntendedCourse.CourseID = _selectedIntendedCourse;

    _newNCSData.CreatedBy = new User(); _newNCSData.CreatedBy.UserId = AuthenticatedUser.UserSingleton.GetSingletonObject().userID; 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.IntendedCourse.CourseID = _registerdCourseId; specialFactorSetUp.SpecialFactor = Convert.ToDecimal(resultGrid["SpecialFactor", i].Value); specialFactorSetUp.SpecialFactorDescription = Convert.ToString(resultGrid["Description", i].Value); specialFactorSetUp.Status = "Active"; specialFactorSetUp.CreatedBy = new User(); specialFactorSetUp.CreatedBy.UserId = AuthenticatedUser.UserSingleton.GetSingletonObject().userID; _newNCSSpecialFactorData.Add(specialFactorSetUp); } _calledFrom = "Save"; if (initialBackground.IsBusy == false) initialBackground.RunWorkerAsync(); MessageBox.Show("Record is save successfully.", "Title", MessageBoxButtons.OK, MessageBoxIcon.Information); RefreshGrid();


    Wednesday, November 21, 2018 9:24 AM

All replies

  • Please post a concise and complete example. At least the entire procedure.

    Wednesday, November 21, 2018 9:45 AM
  • You can try set Visual Studio to break when exception is raised. In menu click Debug then Windows and Exception settings. When you check System.NullReferenceException debugger will stopped at line which caused this exception. It is better solution than try to find it manually.
    Wednesday, November 21, 2018 10:11 AM
  • I agree with Petr B here. Set a breakpoint at the top of this code. then run it. When the breakpoint is hit start stepping through your code. At each point confirm that the data you're reading/writing is correct. The moment a value isn't what you expect you've found your problem. If you get to the RunWorkerAsync call and everything is fine then you'll need to step through that method to see why it failed instead.

    Michael Taylor http://www.michaeltaylorp3.net

    Wednesday, November 21, 2018 3:33 PM
    Moderator
  • Put a try/catch around the code and get the stack trace the will tell you the line number and object that has the problem.
    Wednesday, November 21, 2018 5:30 PM
  • Thank you all for your advises and responses. At this point of time, I become aware how to step through and step into codes. I stepped into the line which gives me error. I tried to change a little bit of codes in BtnSave. Now I am having no runtime error on my UI ,at all, and I can see the data input from UI inside in webservice. However when I check inside database, data still cannot be saved. I did debugging as all suggested. Somewhere I am missing something and I am not sure how to solve. 

    namespace 
    {
        public partial class  : 
        {   
            ServiceClient _Ws = ProxyProperties.Proxy();
            DataTable dtWAF = null;
    
            EnrolmentIntendedCourse[] _intendedCourse = null;
            EnrolmentIntendedCourse[] _intendedCourseList = null;
            NormalisedCompositeScoreSetup[] _WeightageList;
    
            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 _returnCourse;
                    
            RegisteredCourse[] _selectedCourse;
            int _courseType = 0;
    
            NormalisedCompositeScoreSetup _newNCSData = new NormalisedCompositeScoreSetup();
            List<NormalisedCompositeScoreSpecialFactorSetup> _newNCSSpecialFactorData = null;
    
            List<NormalisedCompositeScoreSpecialFactorSetup> _compositeDataSpecialFactor;
    
            NormalisedCompositeScoreSetup[] compositeSetup = null;
    
            DataSet _setupRecords2 = null;
            int RegisterdCourseId = 0;
            int _courseId;
            int _registerdCourseId;
            string _coursename= string.Empty;
            string _studyPeriodDate= string.Empty;
            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();
            }
    
            #region Event
         
    
            private void populateUseInCourse()
            {
                // Prevent the automatic execution of SelectedIndexChanged event while loading the combo box
                cboUseIn.SelectedIndexChanged -= cboUseIn_SelectedIndexChanged;
                ////cboUseIn.DisplayMember = "UseInCourseName";
                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.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[i]["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);
                    }
                }
                resultGrid.Columns.Clear();
                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)
                    {
    
                        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()
            {
                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 = _Ws.GetAllEnrollmentIntendedCourse();
                        _returnCourse =_Ws.GetRegisteredCourseDetail(_registerdCourseId);
                    }
    
                    else if (_calledFrom == "populateUseInCourse")
                    {
                        _intendedCourseList = _Ws.GetAllEnrollmentIntendedCourseByUseInModuleName(_selectedUseInCourse);
                    }
                    else if (_calledFrom == "populateWeightage")
                    {
    
                        _WeightageList = _Ws.GetAllNCSByCourseId(_selectedIntendedCourse);
                        _specialFactorData = _Ws.GetAllNCSSpecialFactorByCourseId(_selectedIntendedCourse);
    
                    }
                    else if (_calledFrom == "Save")
                    {
                        _Ws.SaveNormalisedCompositeSpecialFactorList(_newNCSData, _newNCSSpecialFactorData.ToArray());
                    }
                    else if (_calledFrom == "PopulateStudyPeriod")
                    {
                        _studyPeriods = _Ws.GetStudyPeriods(_courseTypeId);
                    }
    
                    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 = _Ws.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();
    
                        }
    
                        else if (_calledFrom == "populateUseInCourse")
                        {
                            populateIntendedCourse();
                        }
    
                        else if (_calledFrom == "populateWeightage")
                        {
                            populateResultGrid();
    
                            if (_WeightageList != null&& _WeightageList.Length>0)
                            {
    
                                
                                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
    
            #region save btn
            
            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;
                    }
    
                        _newNCSData.WeightingEducationalQualification = Convert.ToDecimal(txtWEQ.Text);
                        _newNCSData.WeightingEducationalAdmissionTest = Convert.ToDecimal(txtWAT.Text);
                        _newNCSData.Status="Active";
                        _newNCSData.IntendedCourse = new Course();
                        _newNCSData.IntendedCourse.CourseID = _registerdCourseId;
                   
                        _newNCSData.EnrolmentIntendedCourse = new Course();//added
                        _newNCSData.EnrolmentIntendedCourse.CourseID = _selectedIntendedCourse; //added
                        _newNCSData.RegisteredCourse = _returnCourse;//added
    
                        _newNCSData.CreatedBy = new User();
                        _newNCSData.CreatedBy.UserId = AuthenticatedUser.UserSingleton.GetSingletonObject().userID;
    
                        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.IntendedCourse = new Course();
                                specialFactorSetUp.IntendedCourse.CourseID = _registerdCourseId;
                                //specialFactorSetUp.RegisteredCourse = new Course();
                                //specialFactorSetUp.RegisteredCourse.RegisteredCourseID = _returnCourse;
                                specialFactorSetUp.RegisteredCourse = _returnCourse;
                                specialFactorSetUp.EnrolmentIntendedCourse = new Course();
                                specialFactorSetUp.EnrolmentIntendedCourse.CourseID = _selectedIntendedCourse;
                                specialFactorSetUp.SpecialFactor = Convert.ToDecimal(resultGrid["SpecialFactor", i].Value);
                                specialFactorSetUp.SpecialFactorDescription = Convert.ToString(resultGrid["Description", i].Value);
                                specialFactorSetUp.Status = "Active";
                                specialFactorSetUp.CreatedBy = new User();
                                specialFactorSetUp.CreatedBy.UserId = AuthenticatedUser.UserSingleton.GetSingletonObject().userID;
          
                                    _newNCSSpecialFactorData.Add(specialFactorSetUp);    
                                
                            
                            }
                            _calledFrom = "Save";
    
                            if (initialBackground.IsBusy == false)
                                initialBackground.RunWorkerAsync();
    
                            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);
                }
    
            }
    
    
             
            #endregion save btn
    
    
    
            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("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));
            }
    
            
     #endregion
    
    
    #region event
            public void cboUseIn_SelectedIndexChanged(object sender, EventArgs e)
            {
                try
                {
                    if (cboUseIn.SelectedIndex != -1)
                    {
                        _selectedUseInCourse = cboUseIn.Text;
                        _calledFrom = "populateUseInCourse";
    
                        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 22, 2018 2:04 AM
  • That's quite possible. You're trying to use a single BackgroundWorker to do all your async work and if there is any overlap it isn't going to behave properly. I really think you need to step back and reconsider your approach. The clear sign to me was when you started using if statements inside of your code to "identify" the call to use. This is a clear sign you're doing something wrong.

    I don't honestly think you need all those async calls but let's assume you do. Create a separate BWC for each one. For each one assign it its own DoWork method and completion event handler. This eliminates the need for your _calledFrom field and if statements. It will dramatically simplify your code.

    The next thing I see is your constructor of your class. You should never do anything in the ctor other than initialize the fields of your form/control. There is no guarantee the instance will ever be rendered so anything that needs to happen only when rendered needs to be moved into the OnLoad method (for forms). In your case the logic you have for loading the data should be moved to the OnLoad method.

    You might also consider using async/await instead of BWC. This would dramatically reduce the amount of code you have to write, eliminates the extra methods you're defining and would be more efficient.

    But to your current problem of the data not saving. Set a breakpoint on the line of code that is saving the data to the database. Because of the interweaving a single BWC to the actual logic it looks like your save button calls the BWC to save. Your BWC makes a web service call so that is where the breakpoint would go. If it never gets there then you need to walk through the logic to find out why. Again, since you're trying to use a single BWC it is quite possible that the actual request will get skipped.

    if the web service call is coming back successful then the problem is either in the web service save logic or how you're retrieving that data. You should verify after the web service call the data is in the database. If it isn't then the service call is either wrong or failing. You'll have to diagnose that. If the data is in the database but you aren't seeing it in your UI then you have a refresh issue. Breakpoints on the appropriate code will help identify what is going wrong here.


    Michael Taylor http://www.michaeltaylorp3.net

    Thursday, November 22, 2018 3:51 AM
    Moderator
  • Does BWC mean BackgroundWorkerComplete?
    Thursday, November 22, 2018 6:12 AM
  • Just some comments:

    I would start with cleaning up the code.

    - Use always visibility modifiers.

    - Unnecessary empty lines. They are either unnecessary or like comments an indicator for missing refactorings like extract method or extract class.

    - Consider moving the service client code into a separate class.

    - Consider moving the data arrays and lists into a separate class (model as in the MVC pattern).

    - Use List<T> instead of arrays. Then you need lesser null test:

    private List<DateRange> studyPeriods = new List<DateRange>();
    foreach (DateRange studyPeriod in this.studyPeriods)
    {
    	studyPeriodDT.Rows.Add(studyPeriod.StartDate.ToString("dd/MM/yy hh:mm:ss tt") + " - " + studyPeriod.EndDate.ToString("dd/MM/yy hh:mm:ss tt"));
    
    }
    
    // instead of
    
    DateRange[] _studyPeriods;
    DateRange studyPeriod= null;
    
    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"));
    
    	}
    }		

    Thus always initialize them.

    - Your using exceptions incorrectly. Message and reason do not correlate:

    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);
    	}
    }

    Also in the above method should no exception happen. Handle them in the BW.

    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);
    	}
    }

    No need for error handling here. MessageBox.Show() and TextBox.Focus() do not raise exceptions. Only ValidationForCalculation() may, but then it should be handled there.

    - Use a more compact Boolean notation. E.g.

    grpCopy.Enabled = ( cboUseIn.SelectedValue.ToString() == "Yes");
    // instead of										
    if( cboUseIn.SelectedValue.ToString() == "Yes")
    {
    	grpCopy.Enabled = true;
    }
    else
    {
    	grpCopy.Enabled = false;
    }
    
    if (!initialBackground.IsBusy)
    	initialBackground.RunWorkerAsync();
    // instead of
    if (initialBackground.IsBusy == false)
    	initialBackground.RunWorkerAsync();
    	
    if (ValidationForCalculation())
    {
    	MessageBox.Show("Data is saved successfully", "Weightage And Special Factor", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    else
    {
    	MessageBox.Show("You have not made any chages.", "Weightage And Special Factor", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    
    txtWAT.Focus();
    return;
    
    // instead of
    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;
    }	

    - Also your approach to validate the user input consists of many over different places distributed snippets(DuplicateRecords, ValidationForCalculation, inlined tests). Consider using one validation method which generates all output at once. Currently you let the user jump from one validation error to the next.


    Thursday, November 22, 2018 10:35 AM
  • BWC is BackgroundWorker Component. The _initialBackground in your code.

    Michael Taylor http://www.michaeltaylorp3.net

    Thursday, November 22, 2018 3:59 PM
    Moderator