title: C# programmatically change selected item in listview
body: <p>Update! </p>
  
  <p>To clarify the question. I would like to change the selected item in my listview by using the up and down arrow. I have tied <strong>keydown</strong> to a textbox. If a user presses the period key i make my listview visible. But it's not focused, that is why I have tied the keydown events to the textbox to be able to change the selecteditem in the listview. </p>
  
  <p>the code that visuaö studio is complaining about is this</p>
  
  <pre><code>index = listView1.SelectedIndices[0];
  </code></pre>
  
  <p>the zero is somehow wrong?</p>
  
  <p>I'm using a <strong>listview</strong>!</p>
  
  <p>How do I change the listview <code>selecteditem</code> programatically? I'm currently listening to to the keypress events of up arrow and down arrow.</p>
  
  <p>As they are pressed I would like to change the selected items index. So that it would behave equally as when pressing up or down arrow having it focused!</p>
  
  <p>I have been trying, but it gives me an ugly error message.</p>
  
  <p>Argument out of range exception with the additional information that goes like this:</p>
  
  <blockquote>
    <p>Value of 0 is not valid for index. Here's my code for down arrow.</p>
  </blockquote>
  
  <p>IT really should work I'm totally clueless about this!</p>
  
  <pre><code>if (e.KeyCode == Keys.Down)
  {
      if (listView1.Visible)
      {
          index = listView1.SelectedIndices[0];  
          index = index - 1;
          this.listView1.Items[index].Selected = true;
      }
  }
  </code></pre>
  
  <p>and for up arrow</p>
  
  <pre><code>if (e.KeyCode == Keys.Up)
  {
      if (this.listView1.Visible)
      {
          index = listView1.SelectedIndices[0];
          index++;
          this.listView1.Items[index].Selected = true;
      }
  }
  </code></pre>