Click here to Skip to main content
15,916,417 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am writing a C# app using a DataGridView bound to a MySQL database. Nothing too unusual, except that I wanted the users to be able to edit data directly in the DGV. To make this work, I used this link as a guide:
Auto Saving DataGridView Rows to a SQL Server Database[^]

I added a right-click context menu to the DGV with some hard-coded filters (Users can't customize). When I filter on one criteria, it works...then I (with another menu) reset it, and that works, but whether I reset it or not, the second time I try to filter on different criteria, I get a null reference exception (see code below).

I understand why it's happening. I am just not sure the best way to fix it. Any help would be appreciated!

C#
	  private void bSource_PositionChanged(object sender, EventArgs e)
	  {
		 bSource.EndEdit();
		 // if the user moves to a new row, check if the last row was changed
		 BindingSource thisBindingSource = (BindingSource)sender;
		 DataRow ThisDataRow = ((DataRowView)thisBindingSource.Current).Row; // <- This is where it breaks
		 if (ThisDataRow == LastDataRow)
		 {
			// we need to avoid writing a datarow to the database when it is still processing. Otherwise
			// we get a problem with the event handling of the DataTable.
			return;
		 }
		 UpdateRowToDatabase();
		 // track the current row for next PositionChanged event
		 LastDataRow = ThisDataRow;
	  }

/* Example for two of the context menu buttons */
	  private void toolStripMenu_40hour_Click(object sender, EventArgs e)
	  {
		 bSource.Filter = "colHours = 40";
	  }
	  private void toolStripMenu_Overtime_Click(object sender, EventArgs e)
	  {
		 bSource.Filter = "colHours = 0 OR colHours > 40";
	  }
	  private void toolStripMenu_Reset_Click(object sender, EventArgs e)
	  {
		 bSource.RemoveFilter();
	  }
Posted
Updated 28-Jul-11 18:40pm
v3

1 solution

Still having trouble with this, if anyone cares to help. If you need more detail or clarification, please let me know as well!
Thanks!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900