2017-06-20 155 views
1

所以,我有一个DataGridViewwhere,我从我的Access数据库中填充信息。 DataGridView中的第一列作为来自我的网络的IP。我正在尝试的是使用键盘上下的箭头,并将每行的信息显示到几个TextBox中。这是代码:在C#中的DataGridView中使用箭头#

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(); 
      } 
     } 
    } 
} 

问题是,点击例如在在DataGridView的第一行,并使用箭头它不会显示正确的信息,而是显示从上述行的信息之后。你知道问题是什么?

回答

1
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(); 
       } 
      } 
     } 
    } 
} 

键按下事件会给当前行,我们需要重写这个按照我们的要求,我已经更新行数为每个键击,这将工作,请试试这个,

+0

它完美地工作。谢谢! – Rekcs

+0

我很高兴能够提供帮助。 –