Reputation: 879
So, I have a DataGridViewwhere I am populating info from my Access database. The first column from the DataGridView as IP's from my Network. What I am trying to do is using the arrows up and down from keyboard and display the information from each row into a couple of TextBox. This is the code:
private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
bool pingable = false;
Ping pinger = new Ping();
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
PingReply reply = pinger.Send(row.Cells[0].Value.ToString());
if (e.KeyCode == Keys.Down)
{
txtIP.Text = row.Cells[0].Value.ToString();
txtUser.Text = row.Cells[1].Value.ToString();
txtComputer.Text = row.Cells[2].Value.ToString();
txtUnity.Text = row.Cells[3].Value.ToString();
txtSession.Text = row.Cells[4].Value.ToString();
if (pingable = reply.Status == IPStatus.Success)
{
pictureBoxGreen.Show();
pictureBoxRed.Hide();
}
else if (pingable = reply.Status == IPStatus.TimedOut)
{
pcGreen.Hide();
pcRed.Show();
}
}
if (e.KeyCode == Keys.Up)
{
txtIP.Text = row.Cells[0].Value.ToString();
txtUser.Text = row.Cells[1].Value.ToString();
txtComputer.Text = row.Cells[2].Value.ToString();
txtUnity.Text = row.Cells[3].Value.ToString();
txtSession.Text = row.Cells[4].Value.ToString();
if (pingable = reply.Status == IPStatus.Success)
{
pictureBoxGreen.Show();
pictureBoxRed.Hide();
}
else if (pingable = reply.Status == IPStatus.TimedOut)
{
pictureBoxGreen.Hide();
pictureBoxRed.Show();
}
}
}
}
The problem is, after clicking for example at the first row of the DataGridView and use the arrows it won't display the right information and instead display the information from the above row. Do you know what could the problem be?
Upvotes: 1
Views: 594
Reputation: 832
private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down)
{
var index = e.KeyCode == Keys.Up ? -1 : e.KeyCode == Keys.Down ? 1 : 0;
var rowIndex = dataGridView1.CurrentCell.RowIndex + index;
if (rowIndex > -1)
{
bool pingable = false;
Ping pinger = new Ping();
var row = dataGridView1.Rows[rowIndex];
if (row != null)
{
PingReply reply = pinger.Send(row.Cells[0].Value.ToString());
txtIP.Text = row.Cells[0].Value.ToString();
txtUser.Text = row.Cells[1].Value.ToString();
txtComputer.Text = row.Cells[2].Value.ToString();
txtUnity.Text = row.Cells[3].Value.ToString();
txtSession.Text = row.Cells[4].Value.ToString();
if (pingable = reply.Status == IPStatus.Success)
{
pictureBoxGreen.Show();
pictureBoxRed.Hide();
}
else if (pingable = reply.Status == IPStatus.TimedOut)
{
pcGreen.Hide();
pcRed.Show();
}
}
}
}
}
Key down event will give current row, we need to override this as per our requirement, i have updated the row count as per key hit, this will work please try this,
Upvotes: 1