// Here is the trick for the Background / Foreground Color // of the Cell - override the Paint method, with our // own functionality. protected override void Paint( System.Drawing.Graphics g, System.Drawing.Rectangle bounds, System.Windows.Forms.CurrencyManager source, int rowNum, // Here is the Row Number System.Drawing.Brush backBrush, System.Drawing.Brush foreBrush, bool alignToRight) { // Do we have Subscribers - notify them if we have if (DataGridDisableCell != null) { // Initialize our Event with the current Row and Column Number DataGridDisableCellEventArgs e = new DataGridDisableCellEventArgs(rowNum, _col); // Notify Subscribers to call their EventHandlers - where they // can do whatever they want. After this we check the EnableValue // Flag, which may be set / unset by a Subscriber. DataGridDisableCell(this, e); // Set the Foreground / Back Color according to our Subscribers if (!e.EnableValue) { backBrush = Brushes.Red; foreBrush = Brushes.White; } } // In any case (enabled or disabled) draw the Column using the Base Method base.Paint(g, bounds, source, rowNum, backBrush, foreBrush, alignToRight); }
// Here is the trick to emable / disable the TextBox // of the Cell - override the Edit method, with our // own functionality. protected override void Edit( System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Rectangle bounds, bool readOnly, string instantText, bool cellIsVisible) { DataGridDisableCellEventArgs e = null; // Do we have Subscribers - notify them if we have if (DataGridDisableCell != null) { // Initialize our Event with the current Row and Column Number e = new DataGridDisableCellEventArgs(rowNum, _col); // Notify Subscribers to call their EventHandlers - where they // can do whatever they want. After this we check the EnableValue // Flag, which may be set / unset by a Subscriber. DataGridDisableCell(this, e); } // Only call the Edit Method (which enables the TextBox in the DataGrid) // when the Enable Flag has been set by the Subscriber if (e.EnableValue) { base.Edit(source, rowNum, bounds, readOnly, instantText, cellIsVisible); } }
// This is our own DataGridDisableCell Handler. Here we can do whatever // we want. Our Handler must conform to the paramters defined in the delegate. public void SetEnableValues(object sender, DataGridDisableCellEventArgs e) { // OK, our sample uses modulo 5 to disable the Cells. Note, that a Cell // has NO disable / enable Flag, this is done by the DataGridTextBoxColumn // Edit Function as follows: // Enable Cell: Call DataGridTextBoxColumn.Edit // Disable Cell: Do not call DataGridTextBoxColumn.Edit if ((e.Column + e.Row) % 2 == 0) { e.EnableValue = false; // Do not call DataGridTextBoxColumn.Edit } else { e.EnableValue = true; // Do not call DataGridTextBoxColumn.Edit } }