开发者

How to fix an issue with DataGridView.RowValidating

开发者 https://www.devze.com 2023-01-19 01:37 出处:网络
I\'m trying to link a DataGridView to a data table in a database. I want the DataGridView to update the data table automatica开发者_JS百科lly (without having to click \"Save\" or anything like that).

I'm trying to link a DataGridView to a data table in a database. I want the DataGridView to update the data table automatica开发者_JS百科lly (without having to click "Save" or anything like that). Seems to me that the best way to do this is by handling the RowValidating event. 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.). Then I press Enter and a new blank row (row #2) appears with no error message. On this new row I enter some other data, erroneous or not, and press Enter again. 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. 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. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消