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.
C# Prevent DataGridView Leave
-
18-10-2022 - |
문제
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.
해결책
다른 팁
As stated by others, the RowLeave event doesn't have an e.Cancel. Try the RowValidating event which does have the e.Cancel available. Got this from: "https://bytes.com/topic/visual-basic-net/answers/440349-vb2005-stop-user-leaving-row-datagridview"
private void Grid_Product_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
Grid_Product.EndEdit(); //it helps for instant value update before leaving.
/// write youre code here...
}
제휴하지 않습니다 StackOverflow