Problem:I want to get inserted characters(AccountID) in cell of datagridview, so that i can get respective username from database. i had stuck in problem that on keypress event of datagridview, it is not getting recently insert char. For example,if user name is 'John Snow' its ID=JN. When I write 'J' in datagridview cell, and get value on keypress, it gets "". when I write further as 'JN', it gets 'J'. similarly, on 'JNE' , it gets 'JN' , so then i get JohnSnow from Database. In short, It get previous value not recently inserted. I have Implement it as,
public DebitCredit()
{
InitializeComponent();
this.KeyPreview = true;
this.KeyPress += new KeyPressEventHandler(Control_KeyPress);
}
private void Control_KeyPress(object sender, KeyPressEventArgs e)
{
//Get the column and row position of the selected cell
int column = DGV_DEBIT_CREDIT.CurrentCellAddress.X;
int row = DGV_DEBIT_CREDIT.CurrentCellAddress.Y;
DataTable result=null;
if (column == 0)
{
string test = DGV_DEBIT_CREDIT[column, row].EditedFormattedValue.ToString();
result = getpro.SearchAccountByID(test);
if (result != null)
{
if (result.Rows.Count > 0)
{
DGV_DEBIT_CREDIT[column, row].Value = result.Rows[0][0].ToString();
DGV_DEBIT_CREDIT[column + 1, row].Value = result.Rows[0][1].ToString();
}
else
{
DGV_DEBIT_CREDIT[column, row].Value = "".ToString();
DGV_DEBIT_CREDIT[column + 1, row].Value = "".ToString();
}
}
}
}
First handle EditingControlShowing
event of DataGridView
as shown below. For the current control getting edited in the datagridview column, handle keyUp
event as shown below.
Then you can see the expected result.
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
e.Control.KeyUp += new KeyEventHandler(Control_KeyUp);
}
private void Control_KeyUp(object sender, KeyEventArgs e)
{
//YOUR LOGIC
// string test = dataGridView1[0, 0].EditedFormattedValue.ToString();
}