Ryan Hansen

Ryan Hansen

  • NA
  • 1
  • 0

DataGridView cellEndEdit and DataSource updates

Sep 29 2008 11:58 AM
Greetings all,

I'm a C# intermediate at best, so forgive any ignorance display in the forthcoming.

I'm using a DataGridView bound to a DataSet of database query results.  I'm trying to handle a pretty common operation of updating the database when a grid cell changes.  I have it all working except for one thing, that I can seem to understand.  I'm using the cellEndEdit event to trigger my update to the database, which works great...sometimes.

It seems that, although the event fires every time I leave the cell after an edit, the dataset it only updated when I actually click with the mouse outside the edited cell.  So, if I edit a cell and then click somewhere else, the event fires, the dataset gets updated, and hence, the database gets updated every time; however, if I edit a cell and then hit "enter" or tab out of the cell, the event still fires, but the dataset is not actually updated, and therefore the database is not updated.

Here's the operative code with comments:

// This is the event handler method
void dgHostsCellChanged(object sender, DataGridViewCellEventArgs e)
        {
            // If you guys know a better way to set these values, I'm all ears
            string newVal = this.dgHosts.Rows[e.RowIndex].Cells[e.ColumnIndex].FormattedValue.ToString();
            string column = this.dgHosts.Columns[e.ColumnIndex].Name;
            string pkey = this.dgHosts.Rows[e.RowIndex].Cells[0].FormattedValue.ToString();
   
            // dsHosts is my dataset which gets loaded in a different method.  It's a public
            // member variable of the MainForm class.
            // db is my custom database object.
            dsHosts = db.updateDSCell(dsHosts, "hosts", e.RowIndex, e.ColumnIndex, newVal);
           
            // My dbms is PostgreSQL, so I have to handle the boolean datatype a little
            // to make it compatible with the db.
            switch (newVal)
            {
                case "True":
                    newVal = "t";
                    break;
                   
                case "False":
                    newVal = "f";
                    break;
            }
           
            // my update statement
            string updateSQL = "UPDATE host SET " + column + "='" + newVal + "' WHERE host_id=" + pkey;
            // as I mentioned, I'm using PostgreSQL, so Npgsql is the connector
            NpgsqlCommand command = new NpgsqlCommand(updateSQL);
            // daHosts is my adapter
            daHosts.UpdateCommand = command;
            daHosts.Update(dsHosts, "hosts");
        }

// this is the updateDSCell method
        public DataSet updateDSCell(DataSet ds, string tableName, int rowIndex, int colIndex, string newVal)
        {   
            ds.Tables[tableName].Rows[rowIndex][colIndex] = newVal;
           
            return ds;
        }

Thanks.

Answers (5)