DataGridView Cell click problem

Hi guys,

Greetings!

I setup an unbound dataGridView. I was able to managed to bind the datasource to my table. Unfortunately, certain problems I experienced and these are listed below:

1. First of, I want to set the first row to be selected

2. I used the CellClick event to handle the get and set of values to my textboxes whenever user click on a particular cell. Below is a souce code I used. Note that I used an if statement (rowIndex > -1) in order for me to escape an error. I'm speaking of this process.

2.1 On the grid, I selected the first row, making the variable rowIndex = 0

2.2 Then I try to sort a column (let say customerName), this will turn to make the first row goes to the second row (assumption here is having two records), obviously variable rowIndex = 1 now

2.3 This makes an error now.... (logically speaking, the details passed to textboxes is the wrong details, then on error part is having to throw a -1 value for the rowIndex...)

private void DataGridViewCellClicked(object sender, DataGridViewCellEventArgs e)

{

int rowIndex = e.RowIndex;

DataGridView row = this.dataGridViewCustomer.SelectedRows();

if (rowIndex > -1)

{

// Get and Set the value. Get the cell value and set to text boxes

this.txtCustomerName.Text = this.dataGridViewCustomer.Rows[rowIndex].Cells[1].Value.ToString();

this.txtCustomerAddress.Text = this.dataGridViewCustomer.Rows[rowIndex].Cells[2].Value.ToString();

this.txtCustomerTelNo1.Text = this.dataGridViewCustomer.Rows[rowIndex].Cells[3].Value.ToString();

this.txtCustomerTelNo2.Text = this.dataGridViewCustomer.Rows[rowIndex].Cells[4].Value.ToString();

this.txtCustomerFax.Text = this.dataGridViewCustomer.Rows[rowIndex].Cells[5].Value.ToString();

this.txtCustomerCellNumber.Text = this.dataGridViewCustomer.Rows[rowIndex].CellsDevil.Value.ToString();

this.txtCustomerContactPerson.Text = this.dataGridViewCustomer.Rows[rowIndex].Cells[7].Value.ToString();

this.txtCustomerCreditLimit.Text = this.dataGridViewCustomer.Rows[rowIndex].CellsMusic.Value.ToString();

}

here's the error message I'm receiving (removing the if statement I wrote above)

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

I want to get rid of the error, set the index properly and set the details to my textboxes in respect to the selected row(record) in the datagridview.

Please guys help me.

Thanks in advance!

Kind regards,



Answer this question

DataGridView Cell click problem

  • davros51

    The column header is a cell, and it's row index is -1. Therefore, when attempting to access a value from row of index -1 you will get an error. Also note the comment about the datagrid view settings in the sample code below.

    using System;

    using System.Collections.Generic;

    using System.ComponentModel;

    using System.Data;

    using System.Drawing;

    using System.Text;

    using System.Windows.Forms;

    namespace WindowsApplication1

    {

    public partial class Form1 : Form

    {

    public Form1()

    {

    InitializeComponent();

    }

    private void Form1_Load(object sender, EventArgs e)

    {

    // begind sample table

    DataTable dt = new DataTable("Test");

    dt.Columns.Add(new DataColumn("One"));

    dt.Columns.Add(new DataColumn("Two"));

    Int16 i =0;

    while (i<10){

    DataRow rw = dt.NewRow();

    rw["One"] = "one " + i.ToString();

    rw["Two"] = "Two " + i.ToString();

    dt.Rows.Add(rw);

    i++;

    }// end while

    // end sample table

    this.dataGridView1.DataSource = dt;

    this.dataGridView1.CellClick += this.CellClick_Handler;

    // Impact on rows selected by cell click

    // without this setting no rows selected by cell click.

    this.dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

    }// end form load

    private void CellClick_Handler(object sender, DataGridViewCellEventArgs e)

    {

    MessageBox.Show(e.RowIndex.ToString());

    // also

    DataGridViewSelectedRowCollection rws = this.dataGridView1.SelectedRows;

    // Selected row count is zero when fullrow select is false

    if (rws != null rws.Count > 0 : false) {

    DataGridViewRow rw = rws[0];

    string ItemText1 = (string)rw.Cells["One"].Value;

    MessageBox.Show(ItemText1);

    }

    }// end cell click handler

    }//end form

    }

    Rgds,

    Martin.


  • ComputerWhiz

    Hi Martin,

    Right, it is not a "bug" of any how, I just used the word error coz I have this at my end better term I guess is "user logical error" :D

    The rowEnter event works great! Magic!

    How about after loading on the datagridview the records, having the first record (row) selected

    Thanks,


  • nikos_22

    Hi Martin,

    Thank you for the reply. I understand why it generates the error clearly now.

    Is there a way to know the index of highlighted row

    Thanks,


  • nickst

    Hi Martin,

    Thank you for the reply, I'll try this later today and hope you wont stop helping me : )

    Thanks,


  • miamikk

    The behaviour of the events is by desing and cannot be classed as an error - particularly s you are handling the selected row index of -1 in your app.

    The RowEnter event has the same signature as cell enter. The cell enter event could also be used for this, but there is no point in capturing the event and invalidating / repainting parts of your form when a user is moving within the same row.

    //.....

    this.dataGridView1.SuspendLayout();

    this.dataGridView1.DataSource = dt;

    //this.dataGridView1.CellClick += this.CellClick_Handler;

    // Impact on rows selected by cell click

    // without this setting no rows selected by cell click.

    //System.Windows.Forms.DataGridViewRowEventHandler hd = this.rowSelectedChanged;

    this.dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

    this.dataGridView1.RowEnter += this.CellClick_Handler;

    this.dataGridView1.ResumeLayout();

    }// end form load

    private void CellClick_Handler(object sender, DataGridViewCellEventArgs e)

    {

    ////MessageBox.Show(e.RowIndex.ToString());

    ////// also

    ////DataGridViewSelectedRowCollection rws = this.dataGridView1.SelectedRows;

    ////// Selected row count is zero when fullrow select is false

    ////if (rws != null rws.Count > 0 : false) {

    //// DataGridViewRow rw = rws[0];

    //// string ItemText1 = (string)rw.Cells["One"].Value;

    //// MessageBox.Show(ItemText1);

    ////}

    // getting row with the cell

    if (e.RowIndex > -1) {

    DataGridViewRow rw = this.dataGridView1.Rows[e.RowIndex];

    string ItemText1 = (string)rw.Cells["One"].Value;

    MessageBox.Show(ItemText1);

    }

    }// end cell click handler

    Happy to be of help,

    Martin.


  • DataGridView Cell click problem