问题
I have a gridview of type datagridview text box column, in that following columns are there:
SrNo | Description | HSNCode | Qty | Rate | Amount
I am generating amount in my program automatically, but I want to check if the user has entered to amount field without entering data in "Rate" then I want to set focus back to the "Rate" field in my program:
I have tried following code:
private void grdData_CellLeave(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 4)
{
if(grdData.Rows[e.RowIndex].Cells[4].Value== null)
{
grdData.CurrentCell = grdData.Rows[e.RowIndex].Cells[4];
}
}
}
But the code is not working.
What should I do to switch focus to the field that is previous to the "Amount"?
Please help.
回答1:
Try:
private void grdData_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (e.ColumnIndex == 5)
{
if(grdData.Rows[e.RowIndex].Cells[3].Value.Equals(""))
{
grdData.ClearSelection();
grdData.Rows[e.RowIndex].Cells[3].Selected = true;
}
}
}
Update - tested and working fine using cellclick
event
private void grdData_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 5)
{
if(grdData.Rows[e.RowIndex].Cells[3].Value.Equals(""))
{
grdData.ClearSelection();
grdData.Rows[e.RowIndex].Cells[3].Selected = true;
}
}
}
回答2:
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
int row = e.RowIndex;
int col = e.ColumnIndex;
if (row < 0 || col != 3)
return;
if (e.FormattedValue.ToString().Equals(String.Empty))
{
}
else
{
double quantity = 0;
try
{
quantity = Convert.ToDouble(e.FormattedValue.ToString());
if (quantity == 0)
{
MessageBox.Show("The quantity can not be Zero", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
e.Cancel = true;
return;
}
}
catch
{
MessageBox.Show("The quantity should be decimal value.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
e.Cancel = true;
return;
}
}
}
回答3:
You can try this piece of code
dgv.ClearSelection();
dgv.Rows[rowindex].Cells[columnindex].Selected = true;
回答4:
Refer following code:
DataGridView1.CurrentCell = dataGridView1[1, 1].Value;
'or
DataGridView1.CurrentCell = DataGridView1.Item("ColumnName", 5)
dataGridView1.BeginEdit(true)
For more assistance, you can follow discussion in following link:
http://www.vbdotnetforums.com/winforms-grids/11313-setting-cell-focus-datagridview.html
Hope its helpful.
来源:https://stackoverflow.com/questions/15918309/set-focus-to-data-grid-view-text-box-column-cell