Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

Overview: I have a Windows Form application, built in .Net 4.7.2 using Visual Studio 2019.  The form has 3 PartID combo boxes, allowing the user to select 3 distinct part IDs from a finite list of parts in the drop down.

 

 

Problem: When the combo box was being filled with values in the drop down list, the following exception was thrown.

 

Exception:

System.AccessViolationException

  HResult=0x80004003

  Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

  Source=<Cannot evaluate the exception source>

  StackTrace:

<Cannot evaluate the exception stack trace>

 

Code:

        private void cbPO_LostFocus(object sender, EventArgs e)

        {

            FillPartID1(poLines);

        }

 

 

        private void cbPO_SelectedIndexChanged(object sender, EventArgs e)

        {

            FillPartID1(poLines);

        }

 

        private void FillPartID1(DataTable poLines)

        {

            AutoCompleteStringCollection acs1 = new AutoCompleteStringCollection();

 

            foreach (var rec in poLines.AsEnumerable())

               acs1.Add(rec.ItemArray[1].ToString());           

 

            cbPartID1.AutoCompleteCustomSource = acs1;

            cbPartID1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;    //Exception thrown here during 2nd execution

            cbPartID1.AutoCompleteSource = AutoCompleteSource.CustomSource;

 

            cbPartID1.DataSource = poLines;

            cbPartID1.DisplayMember = "PART_ID";

            cbPartID1.ValueMember = "PART_ID";

            cbPartID1.SelectedIndex = -1;

        }

 

Cause: The FillPartID1() was being called twice due to event handlers cbPO_SelectedIndexChanged() and cbPO_LostFocus().

 

Solution: Refactor the code so FillPartID1() is called only once.

Comments

Popular posts from this blog

.NET MAUI with Blazor vs. XAML

Deployment Types in AI Foundry

AI Agents vs. Agentic AI