-->

将焦点设置到数据网格视图文本框列单元格(Set focus to Data Grid View Te

2019-08-21 04:06发布

我有型datagridview的文本框列的GridView控件,在下面列有:

SrNo    | Description    | HSNCode    | Qty   | Rate   | Amount

我在我的程序自动生成量,但我要检查,如果用户输入达现场没有“速率”中输入数据,然后我想设置焦点回到我在程序的“费率”字段:

我曾尝试下面的代码:

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];
       }
    }
}

但是,代码是行不通的。
我应该怎么做才能将焦点切换到是先于“数量”字段?
请帮忙。

Answer 1:

尝试:

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;
       }
   }
}

更新-测试,使用精细的工作cellclick事件

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;
       }
   }
}


Answer 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;
                }
            }
        }


Answer 3:

你可以试试这一段代码

dgv.ClearSelection();
dgv.Rows[rowindex].Cells[columnindex].Selected = true;  


Answer 4:

请参阅下面的代码:

DataGridView1.CurrentCell = dataGridView1[1, 1].Value;
'or
DataGridView1.CurrentCell = DataGridView1.Item("ColumnName", 5)

dataGridView1.BeginEdit(true)

如需更多帮助,您可以按照以下链接的讨论:

http://www.vbdotnetforums.com/winforms-grids/11313-setting-cell-focus-datagridview.html

希望它的帮助。



文章来源: Set focus to Data Grid View Text Box Column Cell