从DataGridView获取插入符位置

问题描述 投票:-1回答:1

我正在尝试验证对DataGridView的输入,该输入具有DataGridViewTextBoxCells。文本框单元格可以是有符号的也可以是无符号的,并且可以基于焦点所在的列为int或double。我遇到的问题是按下按键时确定插入符号的位置。

例如,如果单元格允许带符号的双打(脱字号<=>'^'):

  • 一个有效的按键事件:^ 12.3456,按键“-”将给出-12.3456
  • 无效的按键事件:按键为'-'的12.34-56将给出12.34-56

我无法找到任何可让我在按键时进入插入符号位置的东西。

private void SomeGridView_KeyPress(object sender, KeyPressEventArgs e)
{
    DataGridView DGV = SomeGridView;

    string curStr;

    bool isFirst = DGV.CurrentCell.EditedFormattedValue == null;
    curStr = isFirst ? "" : DGV.CurrentCell.EditedFormattedValue.ToString();
    Type type = DGV.CurrentCell.GetType();
    if (DGV.CurrentCell.GetType() == typeof(DataGridViewTextBoxCell))
    {
        DataGridViewTextBoxCell DGVTB = (DataGridViewTextBoxCell)DGV.CurrentCell;
        //Not sure how to get caret here
    }

    switch ((GridDataEnum)DGV.CurrentCell.ColumnIndex)
    {
        case GridDataEnum.setpoint:
        case GridDataEnum.SlopePoint:
            e.Handled = !HelperUtils.isValidNumber(curStr, e.KeyChar, HelperUtils.TargetNumberTypeEnum.signedDouble);
            break;
        case GridDataEnum.lowerX:
        case GridDataEnum.upperX:
        case GridDataEnum.TransX:
        case GridDataEnum.constY:
            e.Handled = !HelperUtils.isValidNumber(curStr, e.KeyChar, HelperUtils.TargetNumberTypeEnum.unsignedDouble);
            break;
    }
}

谢谢

c# datagridview textbox caret
1个回答
0
投票

[如果有其他人正在寻找它,我感谢LarsTech找到了答案。

private void SomeGridView_KeyPress(object sender, KeyPressEventArgs e)
{
    DataGridView DGV = SomeGridView;

    string curStr;

    bool isFirst = DGV.CurrentCell.EditedFormattedValue == null;
    curStr = isFirst ? "" : DGV.CurrentCell.EditedFormattedValue.ToString();
    Type type = DGV.CurrentCell.GetType();
    if (DGV.CurrentCell.GetType() == typeof(DataGridViewTextBoxCell))
    {
        DataGridViewTextBoxCell DGVTB = (DataGridViewTextBoxCell)DGV.CurrentCell;
        if (DGV.CurrentCell.EditType == typeof(DataGridViewTextBoxEditingControl))
            if(DGV.EditingControl != null)
                charIndex = ((TextBox)DGV.EditingControl).SelectionStart;
    }

    switch ((GridDataEnum)DGV.CurrentCell.ColumnIndex)
    {
        case GridDataEnum.setpoint:
        case GridDataEnum.SlopePoint:
            e.Handled = !HelperUtils.isValidNumber(curStr, e.KeyChar, HelperUtils.TargetNumberTypeEnum.signedDouble, charIndex);
            break;
        case GridDataEnum.lowerX:
        case GridDataEnum.upperX:
        case GridDataEnum.TransX:
        case GridDataEnum.constY:
            e.Handled = !HelperUtils.isValidNumber(curStr, e.KeyChar, HelperUtils.TargetNumberTypeEnum.unsignedDouble, charIndex);
            break;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.