Search code examples
c#datagridviewcells

C# Prevent DataGridView Leave


    private void dgvWorkOrder_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
    {
        if (e.ColumnIndex == 0 && e.RowIndex == dgvWorkOrder.RowCount - 1)
        {
            try
            {
                string check = dgvWorkOrder.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Please input a valid entry.", "Empty");
                e.Cancel = true;
            }
        }
        if (e.ColumnIndex == 2 && e.RowIndex == dgvWorkOrder.RowCount - 1) ;
        {
            try
            {
                decimal check = Convert.ToDecimal(dgvWorkOrder.Rows[e.RowIndex].Cells[e.ColumnIndex].Value);
                if (check == 0)
                {
                    throw new Exception();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Please input a valid entry.");
                e.Cancel = true;
            }
        }
    }

With the code above, I'm trying to do a Leave Event that checks if the user inputted anything. If they didn't, I want it so that they can't leave that cell until they do, stopping anything else they can do aside from exiting the program entirely.

Updated as requested.


Solution

  • You just need to use a different event, CellValidating, and set e.Cancel to true if you want to keep the user from leaving the cell. You won't need to set the CurrentCell or BeginEdit using this event.