How can I get the Value of a DataGridViewCell from the Cell_Leave event?
private void dataGridView1_CellLeave(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex > 1)
{
int cellValue = Convert.ToInt32(((DataGridViewCell)sender).Value);
if (cellValue < 20)
{
((DataGridViewCell)sender).Value = 21;
}
开发者_StackOverflow中文版 }
}
I'm trying to get the value of the cell that the event fired from.
An exception is fired when I try to cast sender
to a DataGridViewCell
:
Unable to cast object of type 'System.Windows.Forms.DataGridView' to type 'System.Windows.Forms.DataGridViewCell'.
What do you recommend I do?
I need to check if the value is less than 20, and if it is, bump it up to 21.
Try working with theDataGrid[e.RowIndex, e.ColumnIndex].Value
. I'd expect that the sender is more likely to be the DataGridView object rather than the cell itself.
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.Rows[e.RowIndex].Cells[1].Value != null)
{
int cellmarks = Convert.ToInt16(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value);
if (cellmarks < 32)
{
dataGridView1.Rows[e.RowIndex].Cells[2].Value = "Fail";
}
else
{
dataGridView1.Rows[e.RowIndex].Cells[2].Value = "Pass";
}
}
}
This code will get currentcell value.may this help you.
You can get the value of the cell as
dataGridView1[e.ColumnIndex, e.RowIndex].FormattedValue;
sender's type is DataGridView, so you may use the following line:
int cellValue = Convert.ToInt32(((DataGridView)sender).SelectedCells[0].Value);
I did a slight variant for a _CellClick event.
private void Standard_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
int intHeaderId = 0;
switch (((DataGridView)sender).Columns[e.ColumnIndex].Name)
{
case "grcHeaderId":
intHeaderId = (int)grvEnteredRecords[grcHeaderId.Index, e.RowIndex].Value;
break;
...
I suggest getting the value of the cell using the EditedFormattedValue property, since in my testing the FormattedValue that I have entered is always null.
精彩评论