I have such a problem, I need it when I enter the form programmatically click on the first row of the DataGridView . How can I do it?

  • Click or choose? - Vardan Vardanyan
  • just click. how to highlight I know, but it does not suit me - liorbraiz

2 answers 2

Try this (click on cell [0, 0] ):

 public Form1() { InitializeComponent(); dataGridView1_CellClick(this, new DataGridViewCellEventArgs(0, 0)); } private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { //Ваш код } 
  • 'public Form22 () {InitializeComponent (); dataGridView1_CellClick (this, new DataGridViewCellEventArgs (0, 0)); } private void dataGridView1_CellClick (object sender, DataGridViewCellEventArgs e) {textBox1.Text = dataGridView1.SelectedRows [0] .Cells [1] .Value.ToString (); textBox2.Text = dataGridView1.SelectedRows [0] .Cells [4] .Value.ToString (); } 'error gives this line "textBox1.Text = dataGridView1.SelectedRows [0] .Cells [1] .Value.ToString ();" - liorbraiz
  • @liorbraiz, what exactly is a mistake? - Sv__t
  • Unhandled exception of type "System.ArgumentOutOfRangeException" in mscorlib.dll Additional information: Index out of range. The index must be a positive number, and its size must not exceed the size of the collection. - liorbraiz
  • @liorbraiz, a form is created here with a dataGridView with no initialized values. You try to drive these values ​​into text boxes. What is the main idea of ​​what you want to do in the program? - Sv__t

You can try it is not the best option

  public Form1() { InitializeComponent(); dataGridView1.Rows[0].Selected = true; dataGridView1.Rows[0].Cells[0].Value = "00"; dataGridView1.Rows[0].Cells[1].Value = "01"; dataGridView1.Rows[0].Cells[2].Value = "02"; dataGridView1.Click += DataGridView1_Click; } private void Form1_Load(object sender, EventArgs e) { DataGridView1_Click(sender, e); } private void DataGridView1_Click(object sender, EventArgs e) { listBox1.Items.Add(dataGridView1.Rows[0].Cells[0].Value); listBox1.Items.Add(dataGridView1.Rows[0].Cells[1].Value); listBox1.Items.Add(dataGridView1.Rows[0].Cells[2].Value); } 

A raw exception of type "System.ArgumentOutOfRangeException" in mscorlib.dll

This means that while you are running, the datagridview event is not initialized.
That is, dataGridView1.Rows[0].Cells[0]=null and you are also trying to get the value.