Can I restrict users from selecting a row in a DGV
I have a winform program where I have two datagridviews. They are read-only, so the user cannot edit the values, and have selection mode set to 'entire row'.
My program runs through the dgv one step at a time, highlighting the current row it is working on. For this reason, I do not want a user to be able to click on a row and select it. Is there a setting I can toggle to so this for me?
Or do I have to 开发者_如何转开发get my hands dirty with a SelectionChanged event handler that checks how the selection was changed, and restore it if the user changed selection? If this is the case, how can my SelectionChanged event handler tell if the selection was changed programatically or by the user?
If you want to prevent the user from selecting any rows, you should set the control's Enabled property to false. This will prevent it from accepting mouse events. (You can fiddle with the control colors to make it "look" enabled even if it's disabled.)
If you want to selectively prevent users from selecting certain rows but allow them to select other rows, then you'll need to subclass the DataGridView and override some stuff. (I don't think there's any DGV event that lets you prevent a row change; SelectionChanged happens after the selection has changed, and RowEnter isn't cancellable.)
There is a virtual method called SetSelectedRowCore on the DGV that does the work of actually updating the selected state of a given row. If you override this method you can opt to call or not call the base SetSelectedRowCore() to allow/not allow selection to happen.
You can set the DGV's Enabled
property to false.
This has the effect you want and the DGV doesn't have that 'grayed-out' look when it's not Enabled. You'll also be able to programmatically set the DGV's selected row.
There is a property called "CanSelect" ..
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.canselect.aspx
It seems to be usefull..
精彩评论