简体   繁体   English

如何解决DataGridView.RowValidating问题

[英]How to fix an issue with DataGridView.RowValidating

I'm trying to link a DataGridView to a data table in a database. 我正在尝试将DataGridView链接到数据库中的数据表。 I want the DataGridView to update the data table automatically (without having to click "Save" or anything like that). 我希望DataGridView自动更新数据表(而不必单击“保存”或类似的东西)。 Seems to me that the best way to do this is by handling the RowValidating event. 在我看来,执行此操作的最佳方法是处理RowValidating事件。 I've been testing this code and this is my problem: let's say I add row #1 (row #1, but not necessarily the first row) by typing in the last blank row in the DataGridView and enter some erroneous data (null values where there shouldn't be or text where there should be numbers, etc.). 我一直在测试此代码,这是我的问题:假设我通过在DataGridView输入最后一个空白行并添加一些错误数据(空值)来添加行1(行1,但不一定是第一行)不应有的地方或文本应有的地方等等)。 Then I press Enter and a new blank row (row #2) appears with no error message. 然后按Enter键,新的空白行(第2行)出现,没有错误消息。 On this new row I enter some other data, erroneous or not, and press Enter again. 在这一新行中,我输入其他一些数据,无论是否错误,然后再次按Enter。 Now I get an error message and an error bubble appears on row #1, but the focus is on row #2 and if I try to edit row #1 I get an error message again and the focus stays on row #2. 现在,我收到一条错误消息,并且错误气泡出现在#1行上,但是焦点在#2行上,如果我尝试编辑#1行,我又收到一条错误消息,并且焦点仍然停留在#2行上。 How should I handle this? 我该如何处理?

    public Form1()
    {
        InitializeComponent();
        sqlCeConnection.Open();
        table = new DataTable();
        sqlCeDataAdapter = new SqlCeDataAdapter("SELECT * FROM test", sqlCeConnection);
        SqlCeCommandBuilder cBuilder = new SqlCeCommandBuilder(sqlCeDataAdapter);
        sqlCeDataAdapter.Fill(table);

        BindingSource bSource = new BindingSource();
        bSource.DataSource = table;
        dataGridView1.DataSource = bSource;
    }

    private void dataGridView1_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
    {
        try
        {
            sqlCeDataAdapter.Update(table);
        }
        catch (Exception ex)
        {
            e.Cancel = true;
            MessageBox.Show(ex.Message);
        }
    }

I've got the same issue I'm trying to solve. 我遇到了要解决的相同问题。 I've found something interesting. 我发现了一些有趣的东西。 If you mouse click to newrow cell validation occurs and then row validation. 如果单击鼠标以进行新行单元格验证,然后进行行验证。 However, if you simply press enter, only cell validation occurs. 但是,如果仅按Enter键,则仅发生单元格验证。 I've tried to trap the Enter key to see if I could modify this behavior, but the Enter key doesn't trap on new rows on either KeyUp or KeyDown events. 我试图捕获Enter键以查看是否可以修改此行为,但是Enter键不会捕获KeyUp或KeyDown事件的新行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM