Click here to Skip to main content
16,017,259 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

On my form a have two datagridview:

One datagridview is filled by DataBinding:

C#
private void controlContractePrincipalLoad(object sender, EventArgs e)
       {
           string NumeClientCautat = txtCautaDupaNume.Text;
           this.sClienti.DataSource = SetariAmanet.TotiClienti(NumeClientCautat);
       }


A CellContentClick EVENT (its works):

C#
private void dVizualizareClientiCellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            DataGridView vizualizare = sender as DataGridView;
            if (vizualizare != null)
            {
                IdClientSelectat = Convert.ToInt32(vizualizare.SelectedRows[0].Cells[0].Value.ToString());
                if (IdClientSelectat != 0)
                {
                    InformatiiDespreClientContracte();
                }
            }
        }


AND a SelectionChanged event:

C#
private void dVizualizareClientiSelectionChanged(object sender, EventArgs e)
        {
            DataGridView vizualizare = sender as DataGridView;
            if (vizualizare != null)
            {
                IdClientSelectat = Convert.ToInt32(vizualizare.SelectedRows[0].Cells[0].Value.ToString());
                if (IdClientSelectat != 0)
                {
                    InformatiiDespreClientContracte();
                }
            }
        }


The SelectionChanged event is not working
The error massage is: Index out of range.

The SelectionChanged event is executed two times (i think), the first time my IdClientSelectat hase a value, then he gives me an error at this line:

C#
IdClientSelectat = Convert.ToInt32(vizualizare.SelectedRows[0].Cells[0].Value.ToString());


Where is the problem?
Posted

1 solution

The Selection changed event happens a number of times - and one of those times is when the control is first created, and before it gets any data. At this point, your use of absolute values causes an "out of range" exception because there are no rows to work with, and no columns yet either.

Add checking:
C#
if (vizualizare != null && vizualizare.Rows.Count > 0 && vizualizare.Columns.Count > 0)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900