A NullReferenceException exception in System.Windows.Forms.DataGridView - winforms

I have a .NET 4.0 WinForms application. A Form of the application contains a Grid – an System.Windows.Forms.DataGridView object
Suddenly I have got a (non-reproducible!) NullReferenceException in it. The call stack was the following:
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Windows.Forms.DataGridView.UnwireEditingControlEvents()
at System.Windows.Forms.DataGridView.EndEdit(DataGridViewDataErrorContexts context, DataGridViewValidateCellInternal validateCell, Boolean fireCellLeave, Boolean fireCellEnter, Boolean fireRowLeave, Boolean fireRowEnter, Boolean fireLeave, Boolean keepFocus, Boolean resetCurrentCell, Boolean resetAnchorCell)
at System.Windows.Forms.DataGridView.SetCurrentCellAddressCore(Int32 columnIndex, Int32 rowIndex, Boolean setAnchorCellAddress, Boolean validateCurrentCell, Boolean throughMouseClick)
at System.Windows.Forms.DataGridView.set_CurrentCell(DataGridViewCell value)
at System.Windows.Forms.DataGridView.OnClearingRows()
at System.Windows.Forms.DataGridViewRowCollection.ClearInternal(Boolean recreateNewRow)
at System.Windows.Forms.DataGridView.RefreshRows(Boolean scrollIntoView)
at System.Windows.Forms.DataGridView.DataGridViewDataConnection.ProcessListChanged(ListChangedEventArgs e)
at System.Windows.Forms.DataGridView.DataGridViewDataConnection.currencyManager_ListChanged(Object sender, ListChangedEventArgs e)
at System.Windows.Forms.CurrencyManager.OnListChanged(ListChangedEventArgs e)
at System.Windows.Forms.CurrencyManager.List_ListChanged(Object sender, ListChangedEventArgs e)
at System.Windows.Forms.BindingSource.OnListChanged(ListChangedEventArgs e)
at System.Windows.Forms.BindingSource.InnerList_ListChanged(Object sender, ListChangedEventArgs e)
at System.ComponentModel.BindingList`1.OnListChanged(ListChangedEventArgs e)
at System.ComponentModel.BindingList`1.FireListChanged(ListChangedType type, Int32 index)
at System.ComponentModel.BindingList`1.ClearItems()
at System.Collections.ObjectModel.Collection`1.Clear()
at <My Code>;
The calls method Clear of a BindingList-derived list. The BindingList-derived list is, in turn, used in a BindingSource object. The BindingSource object is a datasource of the DataGridView.
I cannot understand – why this happens? And why it happens only sometimes? (to the moment I have seen the problem only once).
And how can this be avoided?

Ran into this myself just now. In my case, I noticed it only happens if the grid has more than about 10 rows or so and you immediately try to go to the last row. My workaround was, after setting the BindingSource, to manually set the current cell to a cell within the first row:
grdConditions.DataSource = myDataSource;
if (grdConditions.Rows.Count > 0)
grdConditions.CurrentCell = grdConditions[0, grdConditions.RowCount - 1];
Seemed to fix the issue for me.

Related

Silverlight Application throwing Null reference Exception on clearing list which is bound to Grid

In Silverlight Application I have bound one ObservableCollection to Grid.
But when I edit row of grid,I am saving updated data in db and clear observable collection of grid and reinsert new values in it.
but when I try to clear observable collection it is throwing an error "Object reference not set to an instance of an object"
Am I missing Anything here.
Code:
MyList.Clear();
StackTrace of Exception
at
Infragistics.AutomationPeers.CellsPanelAutomationPeer.Row_PropertyChanged(Object
sender, PropertyChangedEventArgs e)\r\n at
System.ComponentModel.PropertyChangedEventHandler.Invoke(Object
sender, PropertyChangedEventArgs e)\r\n at
Infragistics.RecyclingContainer1.OnPropertyChanged(String name)\r\n
at Infragistics.Controls.Grids.Row.SetSelected(Boolean isSelected)\r\n
at
Infragistics.Controls.Grids.Row.Infragistics.ISelectableObject.SetSelected(Boolean
isSelected)\r\n at
Infragistics.Controls.Grids.SelectedCollectionBase1.InternalRemoveItemSilently(Int32
index)\r\n at
Infragistics.Controls.Grids.SelectedCollectionBase1.RemoveItem(Int32
index)\r\n at Infragistics.Collections.CollectionBase1.Remove(T
item)\r\n at
Infragistics.Controls.Grids.RowsManager.InvalidateSelectionAndActivation(Boolean
validateInList, Boolean invalidateSelection)\r\n at
Infragistics.Controls.Grids.RowsManager.InvalidateItemSource(Boolean
invalidateSelection)\r\n at
Infragistics.Controls.Grids.RowsManager.DataManager_CollectionChanged(Object
sender, NotifyCollectionChangedEventArgs e)\r\n at
Infragistics.DataManagerBase.OnCollectionChanged(NotifyCollectionChangedEventArgs
e)\r\n at
Infragistics.DataManagerBase.OnDataSourceCollectionChanged(NotifyCollectionChangedEventArgs
e)\r\n at
Infragistics.DataManager1.OnDataSourceCollectionChanged(NotifyCollectionChangedEventArgs
e)\r\n at
Infragistics.DataManagerBase.DataSource_CollectionChanged(Object
sender, NotifyCollectionChangedEventArgs e)\r\n at
System.Collections.ObjectModel.ObservableCollection1.OnCollectionChanged(NotifyCollectionChangedEventArgs
e)\r\n at
System.Collections.ObjectModel.ObservableCollection1.ClearItems()\r\n
at System.Collections.ObjectModel.Collection1.Clear()\r\n at

DataGridView row formatting based on hidden column

Is there any way to set the style of a row based on some value from a column that is not visible to the user? The grid contains a couple of rows and I want some rows to be colored in red if they were deleted. I have a hidden column that stores true if the columns were deleted, false otherwise. I've tried CellFormatting but since my column is not visible, e.ColumnIndex never has the correct value for my hidden column.
Any help will be greatly appreciated.
Edit:
Below is an image of what I am trying to accomplish. You can see that the second row has the text red which is due to the values in a column that the user cannot see in the datagrid. This grid should be colored like this when the user see the form for the first time too (on load).
Instead of CellFormatting, try CellValueChanged for unbound data or DataBindingComplete for a bound data set. For example, let's say that you are "deleting/undeleting" a row using the following Button.Click event:
private void Button1_Click(object sender, EventArgs e)
{
bool value = (bool)dataGridView1.CurrentRow.Cells["Deleted"].Value;
dataGridView1.CurrentRow.Cells["Deleted"].Value = !value;
// For bound data (like a DataTable) add the following line:
// ((DataTable)dataGridView1.DataSource).AcceptChanges();
}
Unbound Data
Changing the rows "deleted" column value in this way will trigger the following event handler. Therefore, you can color your row based on that column's value of True or False:
private void DataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == dataGridView1.Columns["Deleted"].Index)
{
dataGridView1.Rows[e.RowIndex].DefaultCellStyle.ForeColor = (bool)dataGridView1[e.ColumnIndex, e.RowIndex].Value ? Color.Red : Color.Black;
}
}
Bound Data
For bound data, such as from a DataTable, handling the DataBindingComplete event will be enough. This event will trigger when the binding is first set as well as after changes - such as the changes from the Button1.Click event. Here, you'll loop through the rows and set the desired style according to the hidden column's value. (Note the additional change to the Button1_Click event handler for a grid with a DataTable source. This is needed to give an immediate style change - otherwise it won't happen until you navigate to a different row.)
private void DataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
row.DefaultSCellStyle.ForeColor = (bool)row.Cells["Deleted"].Value ? Color.Red : Color.Black;
}
}
Based on my understanding, you want to get a column's value when the column is a invisible column in DataGridView.
Is it right? Please correct me if I'm wrong.
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = CreateDataTable();
dataGridView1.Columns["ID"].Visible = false; // Set the ID column invisible.
MessageBox.Show(dataGridView1.Rows[2].Cells["ID"].Value.ToString()); // Get the ID column value.
}

Windows Phone 8.1 app shows exception "Value does not fall within the expected range."

In first page I tap an image to view in large. This tapping event takes me to another second page. In this second page I zoom in or out the image. After that I press back key and come back to the first page. Then it throws this error message.
Value does not fall within the expected range.
System.ArgumentException: Value does not fall within the expected range.
at MS.Internal.XcpImports.MethodEx(IntPtr ptr, String name, CValue[] cvData)
at MS.Internal.XcpImports.MethodPack(IntPtr objectPtr, String methodName, Object[] rawData)
at MS.Internal.XcpImports.UIElement_TransformToVisual(UIElement element, UIElement visual)
at System.Windows.UIElement.TransformToVisual(UIElement visual)
at Microsoft.Phone.Controls.GestureListener.GetInverseTransform(Boolean includeOffset, UIElement target)
at Microsoft.Phone.Controls.GestureListener.OnPinchCompleted(ManipulationDeltaEventArgs lastPinchInfo, Boolean gestureCompleted)
at Microsoft.Phone.Controls.GestureListener.OnManipulationDelta(Object sender, ManipulationDeltaEventArgs e)
at MS.Internal.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args)
at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, Int32 actualArgsTypeIndex, String eventName)
I am trying to find out the reason and solution of this problem but failed. I am looking for fruitfull answers to this question.

WPF radiobutton event handling questions

radio.Checked += new RoutedEventHandler(VariantChecked);
assuming I have this code. What if I want to pass an argument to VariantChecked method. What syntax should I apply?
During creation, attach your data object to the DataContext or the Tag property of the RadioButton.
RadioButton radio=new RadioButton();
radio.DataContext=yourData;
Then in the event handler, get the data back:
void VariantChecked(object sender, RoutedEventArgs e){
RadioButton radio=(RadioButton)sender;
YourData yourData=(YourData)radio.DataContext;
}
In the above example I have assumed that you have a class or struct named YourData that you want to provide. You can replace this through any primitive like string or int or any other object type.
The above works also from xaml:
<RadioButton Tag="Static Data, could also be a binding" ...
Here I have taken the Tag property because it makes for such a construction more sense, but DataContext could also be taken. The event handler is the same except for casting from the Tag-property.
void VariantChecked(object sender, RoutedEventArgs e){
RadioButton radio=(RadioButton)sender;
string yourStringFromTag=(string)radio.Tag;
}
By the way, you can make the code more generic by not specify a concrete control-class but a base class:
void VariantChecked(object sender, RoutedEventArgs e){
FrameworkElement fe=(FrameworkElement)sender;
string yourStringFromTag=(string)fe.Tag;
}
Hope this helped...

Silverlight Application Error 0x17F8 on ComboBox_DropDownOpened

I have several similar comboboxes with custom templates that display one custom control on the dropdown. Suddenly one of those controls have broken and they give me the following error when I open the combobox.
Message: Unhandled Error in Silverlight 2 Application Error 0x17F8. Debugging resource strings are unavailable. See http://go.microsoft.com/fwlink/?linkid=106663&Version=4.0.50401.0&File=mscorrc.dll&Key=0x17F8 at <INSERT_NAMESPACE>.ComboBox_DropDownOpened(Object sender, EventArgs e)
at System.Windows.Controls.ComboBox.OnDropDownOpened(EventArgs e)
at System.Windows.Controls.ComboBox.OnIsDropDownOpenChanged(Boolean isDropDownOpen)
at System.Windows.Controls.ComboBox.OnIsDropDownOpenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
at System.Windows.DependencyObject.RaisePropertyChangeNotifications(DependencyProperty dp, Object oldValue, Object newValue)
at System.Windows.DependencyObject.UpdateEffectiveValue(DependencyProperty property, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, ValueOperation operation)
at System.Windows.DependencyObject.SetValueInternal(DependencyProperty dp, Object value, Boolean allowReadOnlySet)
at System.Windows.DependencyObject.SetValue(DependencyProperty property, Boolean b)
at System.Windows.Controls.ComboBox.ElementDropDownToggle_Click(Object sender, RoutedEventArgs e)
at System.Windows.Controls.Primitives.ButtonBase.OnClick()
at System.Windows.Controls.Primitives.ToggleButton.OnClick()
at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
at System.Windows.Controls.Control.OnMouseLeftButtonUp(Control ctrl, EventArgs e)
at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, String eventName)
Line: 1
Char: 1
Code: 0
As you can see this only happens in deployed release versions and on the machines with no development environments. The same release version (and debug version) is working on my development machine.
I wrapped everything on the DropDownOpened event handler inside a try-catch-block to get more information but the catch doesn't fire at all.
I tried to Google the error but so far haven't found anything that would be helpful. Any advice how to start solving this? Could this be related to Silverlight runtime version or something that should be installed on the release machines as well?
I managed to solve the issue. I installed Developer Runtime to the machine for the hope that it would reveal better error message from the Exception. And it did! The issue was in the code of the control that was being displayed in the combobox dropdown. I fixed the bug and it's now working fine. Apparently even the strangest error message can mean the simplest thing :)
I wonder if there is a drawback on having the developer runtime instead of the standard runtime?

Resources