datagrid视图中的keypress事件?

时间:2011-12-28 18:38:33

标签: c# datagridview

我需要编写一个简单的函数,当人输入数量时,然后按下按键事件并number of boxes*someamount进入金额列。我使用拖放控件添加了datagridview

我认为根据我的研究,这里将编写代码

private void dataGridView1_EditingControlShowing(object sender,
    DataGridViewEditingControlShowingEventArgs e) {

}

但我不知道如何放置Keyup事件和访问列numberofboxes and Amount。感谢

2 个答案:

答案 0 :(得分:7)

我已经对此进行了测试,它通过使用按键事件工作并将NumberBoxes值乘以someAmount,每次在单元格中输入新数字时,它会自动为您计算

        public Form1()
    {
        InitializeComponent();
        MyDataGridViewInitializationMethod();
    }


    private void MyDataGridViewInitializationMethod()
    {

        dataGridView1.EditingControlShowing +=
    new DataGridViewEditingControlShowingEventHandler(dataGridView1_EditingControlShowing);
    }

    private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        e.Control.KeyPress +=
            new KeyPressEventHandler(Control_KeyPress);
    }

    private void Control_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (char.IsNumber(e.KeyChar))
        {

            string cellValue = Char.ToString(e.KeyChar);
            //Get the column and row position of the selected cell
            int column = dataGridView1.CurrentCellAddress.X;
            int row = dataGridView1.CurrentCellAddress.Y;

            if (column == 1)
            {
            //Gets the value that existings in that cell
            string test = dataGridView1[column, row].EditedFormattedValue.ToString();
            //combines current key press to the contents of the cell
            test = test + cellValue;
            int intNumberBoxes = Convert.ToInt32(test);
            //Some amount to mutiple the numberboxes by
            int someAmount = 10;
            dataGridView1[column + 1, row].Value = intNumberBoxes * someAmount;
            }
        }
    }


}

答案 1 :(得分:0)

for vb.net

十进制验证:

 Public Sub New()
        InitializeComponent()
        MyDataGridViewInitializationMethod()
    End Sub
    Private Sub MyDataGridViewInitializationMethod()
        AddHandler dataGridView1.EditingControlShowing, AddressOf dataGridView1_EditingControlShowing
    End Sub
    Private Sub dataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As DataGridViewEditingControlShowingEventArgs)
        AddHandler e.Control.KeyPress, AddressOf Control_KeyPress
    End Sub
    Dim dotOnce As Boolean
    Private Sub Control_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs)
        If e.KeyChar Like "[']" Then
            e.Handled = True
            Exit Sub
        End If
        If e.KeyChar = "." Then
            If dotOnce Then
                e.Handled = True
            End If
            dotOnce = True
        Else
           If (Not e.KeyChar Like "[0-9 . ]") Then
                e.Handled = True
                Exit Sub
            End If
        End If
          End Sub