I have 4 columns in a DataGridView (dgv). Requested by the user, they want to be able to enter the values into the first 2 columns and when they hit tab have it move to the next row. When they click on the 3rd or 4rd columns then it would allow them to enter data into them.
So far I am attempting to dirrect this behavior in the Cell Events. When I do this, either I geta StackOverflowException/Invalid Operationwhen trying to set CurrentCell, or it appears to move the cell(indebug, current cell is nowset to the cellI want), but I believe is reset to the next field by the datagridview.
Am I approaching this from the right direction or is there something I am missing?
Thanks
Here is the code that I am using to test the feasibilty of the user's request:
public partial class Form1 : Form
{
bool LeavingASA = false;
bool TargetMod1or2 = false;
bool MovingToNextRow = false;
public Form1()
{
InitializeComponent();
// Set up a dataset with three columns (cpt and asa are required stops)
// mod1 and mod2 are optional/rarely used.
DataSet ds = new DataSet();
ds.Tables.Add( "cptcodes" );
ds.Tables[0].Columns.Add( "cpt", typeof( string ) );
ds.Tables[0].Columns.Add( "asa", typeof( string ) );
ds.Tables[0].Columns.Add( "mod1", typeof( string ) );
ds.Tables[0].Columns.Add( "mod2", typeof( string ) );
//setup datagrid view
dgv.ColumnCount = 4;
dgv.EditMode = DataGridViewEditMode.EditOnEnter;
dgv.Columns[0].Name = "CPT Code";
dgv.Columns[1].Name = "ASA Code";
dgv.Columns[2].Name = "Mod 1";
dgv.Columns[3].Name = "Mod 2";
dgv.AutoGenerateColumns = false;
dgv.DataSource = ds;
dgv.DataMember = "cptcodes";
dgv.Columns[0].DataPropertyName = "cpt";
dgv.Columns[1].DataPropertyName = "asa";
dgv.Columns[2].DataPropertyName = "mod1";
dgv.Columns[3].DataPropertyName = "mod2";
// add event handlers
dgv.CellMouseDown += new DataGridViewCellMouseEventHandler( dgv_CellMouseDown );
dgv.CellEnter += new DataGridViewCellEventHandler( dgv_CellEnter );
}
//try to set currentcell before dgv begin edit
void dgv_CellEnter( object sender, DataGridViewCellEventArgs e )
{
//We have move to column index 2 without using a mouse
if ( e.ColumnIndex == 2 && !this.TargetMod1or2 )
{
// If current row is not the newrow
if ( dgv.NewRowIndex != dgv.CurrentRow.Index )
{
//Lets move to the next row (new or not)
if ( !this.MovingToNextRow )
{
//Set moving to true just incase event firings cause this to execute again
this.MovingToNextRow = true;
dgv.CurrentCell = dgv[0, e.RowIndex + 1];
this.MovingToNextRow = false;
}
}
else
{
//Eventually set this to move to the next control in the tab order
}
}
this.TargetMod1or2 = false;
}
//Note that user clicked on the cells we want to allow access to by mouse only
void dgv_CellMouseDown( object sender, DataGridViewCellMouseEventArgs e )
{
if ( e.ColumnIndex == 2 || e.ColumnIndex == 3 )
this.TargetMod1or2 = true;
else
this.TargetMod1or2 = false;
}
}