About datagridview control's event - c#

I'm developed an application for the datagridview filtering . And i used the datagridview's dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
event for filtering.
But i want to handle it on the key press event for the datagridview cell. But i'm not getting that type of event.
the datagridview event should occure
on the each keypress..
So can anybody tell me that which event should i use for the datagridview?
please help me...
thanx

The DataGridView.KeyPress event will not be raised when the user types in a particular cell. If you want to be notified each time they press a key while editing content in a cell, you have two options:
Handle the KeyPress event that is raised directly by the editing control itself (which you can access using the EditingControlShowing event).
For example, you might use the following code:
public class Form1 : Form
{
public Form1()
{
// Add a handler for the EditingControlShowing event
myDGV.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(myDGV_EditingControlShowing);
}
private void myDGV_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
// Ensure that the editing control is a TextBox
TextBox txt = e.Control as TextBox;
if (txt != null)
{
// Remove an existing event handler, if present, to avoid adding
// multiple handler when the editing control is reused
txt.KeyPress -= new KeyPressEventHandler(txt_KeyPress);
// Add a handler for the TextBox's KeyPress event
txt.KeyPress += new KeyPressEventHandler(txt_KeyPress);
}
}
private void txt_KeyPress(object sender, KeyPressEventArgs e)
{
// Write your validation code here
// ...
MessageBox.Show(e.KeyChar.ToString());
}
}
Create a custom class that inherits from the standard DataGridView control and override its ProcessDialogKey method. This method is designed to process each key event, even those
that occur on the editing control. You can either handle the key presses inside of that overridden method, or raise an event of your own to which you can attach a separate handler method.

Related

Cancel Edit Cell on Double Click DataGridView C# WinForm

I have double click event in DataGridView like below :
private void gridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
// put something here to cancel the edit
Form dialogForm = new dialogContainerForm(username);
dialogForm.ShowDialog(this);
}
When this double click fired, it will call another form, and when this child form closed, it will load the grid :
public void callWhenChildClick(List<string> codes)
{
//some code here
Grid_Load();
}
I have cell validating which always fired when this Grid_Load() called :
private void gridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
string code = e.FormattedValue.ToString();
string headerText = gridView.Columns[e.ColumnIndex].HeaderText;
if (!headerText.Equals("No. Transaksi")) return;
if (string.IsNullOrEmpty(code))
{
MessageBox.Show("No. Transaksi tidak boleh kosong!");
e.Cancel = true;
}
}
How to ignore this cell validating just for this case Grid_Load()? Or is there any function to cancel the edit and ignore validating when the cell double clicked?
If you need to prevent an event handler from executing, it can be temporarily removed from the Object and then re-applied when you want it to run again.
To disable (actually remove) an event handler, add the code:
gridView.CellValidating -= gridView_CellValidating
After this line you can run what ever code you want to without it causing the event handler to execute.
The event handler can then be reset or added afresh by adding the line:
gridView.CellValidating += gridView_CellValidating
Note: Each time you are looking to add an event handler like above, you should also precede the call with a remove action to prevent the event handler from executing more than once (or more than the expected number of times). If the event handler hasn't been added and you attempt to remove it, there will be no side-effects, however, multiple additions of the same event handler will cause the event handler to execute multiple times.

Prevent Event Handler

I have a Gridview. I and populating two dynamic text box for each cell inside it. User will enter the arriving time in first textbox and the arriving + 9 hours will be added and display in second textbox. I have written event handler where i am calculating exit time. the event handler is working fine but I need to event handler will fire for first Cell only. How to prevent event handler for rest of the textbox.
You didn't provide code but this is a general example.
private bool _isFirst = true;
private void CellEventHandler(object sender, EventArgs e)
{
if (!_isFirst) return;
// code
_isFirst = false;
}
You could also unbind the event handler
private void CellEventHandler(object sender, EventArgs e)
{
// your code here
textBox.Click -= CellEventHandler;
}

How i can cancel editing datagridview by clicking button if dataerror?

I have DataGridView and button.
DataGridView myDataGridView = new DataGridView();
Button cancelBtn = new Button();
I subscribe on event
myDataGridView.DataError += myDataGridView_DataError;
cancelBtn.Click += cancelBtn_Click;
And my event handlers
void myDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
//show error message
MessageBox.Show(e.Exception.Message);
//set to editing element original value
curRowDataGrid.CancelEdit();
}
void cancelBtn_Click(object sender, EventArgs e)
{
curRowDataGrid.CancelEdit();
//and some specific additional logic
}
But if i click on cancelBtn (if before clicking i wrote wrong value) I do not get to the event handler cancelBtn_Click, i get to myDataGridView_DataError and stay there.
I want following logic: no matter what I typed data if i click on cancelBtn i want get to cancelBtn_Click().
Though the cancel button is clicked, before the click event of cancel button some un-handled exception in the page could have caused because of the wrong data you have provided, the request goes to the DataError Event handler.
Better, implement proper exception handling in your code , suppress exceptions you don't want to fire.

dataGridView ComboBox Event Handler Problem

I am having a problem with the handling of an index changed event for a comboBox that resides inside a dataGridView. I write an method to handle the comboBox selection change using either a delegate:
ComboBox.SelectedIndexChanged -= delegate { ComboBoxIndexChanged(); };
ComboBox.SelectedIndexChanged += delegate { ComboBoxIndexChanged(); };
or an EventHandler:
comboBox.SelectedIndexChanged += new EventHandler(ComboBoxIndexChanged);
but both methods do not work as expected. That is, when you click on your selection within the comboBox (contained within the dataGridView) it takes multiple clicks to cause my ComboBoxIndexChanged(); method to function proper, that if it decides to function at all. What is the best way to overcome/go-about specifying an event on an indexedChange of a comboBox within a dataGridView?
The code I am currently using in context is as follows:
private void dataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
try
{
if (this.dataGridView.CurrentCell.ColumnIndex == (int)Column.Col)
{
ComboBox comboBox = e.Control as ComboBox;
if (comboBox != null)
{
comboBox.SelectedIndexChanged += new EventHandler(ComboBoxIndexChanged);
}
}
return;
}
catch (Exception Ex)
{
Utils.ErrMsg(Ex.Message);
return;
}
}
and the event ComboBoxIndexChanged is:
private void ComboBoxIndexChanged(object sender, EventArgs e)
{
// Do some amazing stuff...
}
I have read a similar thread on StackOverFlow which states that there is a problem with dealing with the comboBox change event this way, but I cannot get the solution to work. The post can be found here: "SelectedIndexChanged" event in ComboBoxColumn on Datagridview. It says:
"Things get complicated since they optimized the DataGridView by only having one editing control for all the rows. Here's how I handled a similar situation:
First hook up a delegate to the EditControlShowing event:
myGrid.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(
Grid_EditingControlShowing);
...
Then in the handler, hook up to the EditControl's SelectedValueChanged event:
void Grid_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
ComboBox combo = e.Control as ComboBox;
if (combo != null)
{
// the event to handle combo changes
EventHandler comboDelegate = new EventHandler(
(cbSender, args) =>
{
DoSomeStuff();
});
// register the event with the editing control
combo.SelectedValueChanged += comboDelegate;
// since we don't want to add this event multiple times, when the
// editing control is hidden, we must remove the handler we added.
EventHandler visibilityDelegate = null;
visibilityDelegate = new EventHandler(
(visSender, args) =>
{
// remove the handlers when the editing control is
// no longer visible.
if ((visSender as Control).Visible == false)
{
combo.SelectedValueChanged -= comboDelegate;
visSender.VisibleChanged -= visibilityDelegate;
}
});
(sender as DataGridView).EditingControl.VisibleChanged +=
visibilityDelegate;
}
}"
This issue I have with this is that "VisSender" is not defined hence the event "VisibleChanged" cannot be used.
Any help from you lads, is as always, most appreciated.
Sounds like you want the changes to be committed as soon as the user changes the drop down box, without them having to click off of the cell. In order to do this you will need to force the commit when the change happens (using CommitEdit, there is also an example on the MSDN page). Add this to your DataGridView:
// This event handler manually raises the CellValueChanged event
// by calling the CommitEdit method.
void dataGridView1_CurrentCellDirtyStateChanged(object sender,
EventArgs e)
{
if (dataGridView1.IsCurrentCellDirty)
{
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
Then you could just listen for the CellValueChanged and avoid having to try and register for the ComboBoxValueChanged event on the underlying editing control.

DataGridView CellFormatting Event Not Firing

I've added a handler for the CellFormatting event on a DataGridView to modify the background color based on the content of the row.
It doesn't seem to be firing even as data gets inserted into the table. I added the event handler by doubleclicking in the IDE on the CellFormatting event which seemed to create the code properly.
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
// this never gets called
MessageBox.Show("Event fired");
}
What could I be doing wrong?
I think you cannot use CellFormating event for your case. It occurs when the contents of a cell need to be formatted for display.
Try CellValueChanged event instead (http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellvaluechanged.aspx)
Or
Select other appropriate event from http://msdn.microsoft.com/en-us/library/x4dwfh7x.aspx
You could try the RowValidated event:
private void dataGridView1_RowValidated(object sender, DataGridViewCellEventArgs e)
{
dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Blue;
}
NOTE: This event will fire when you click on rows and when you close the form.

Categories