Click here to Skip to main content
15,890,973 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi
In window application, I am binding a "DataGridView" DataSource to list of objects. The DGV contains 3 columns. First two column are Simple DataGridViewTextBoxColumn & in 3rd column is type of DataGridViewButtonColumn. It work good but I want to change the name (like Add/Edit) of Button according to some value of Source when adding the rows to gridview. So to this I use RowsAdded event. The Code is
C#
private void gridMappings_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            if (this.gridMappings.DataSource != null)
            {
                int lastRow = this.gridMappings.Rows.Count - 1;

                for (int i = 0; i < this.gridMappings.Rows.Count; i++)
                {
                    if (this.gridMappings.Rows[i] != null)
                    {
                        this.gridMappings.Rows[i].Cells[2].Value = "Add";
                    }
                    else
                    {
                        this.gridMappings.Rows[i].Cells[2].Value = "Edit";
                    }
                    
                }
            }
        }


It work perfect but after adding the row to gridview, When I click anywhere on grid I am getting error "Index -1 does not have a value." in Program.cs file.

Please help !
Thanks
Posted
Comments
Sinisa Hajnal 26-Sep-14 2:22am    
Set a breakpoint in any other grid handlers you have in your code. I don't think this code causes it.

Try calling gridMappings.CommitEdit. Or Refresh. Or Update. :) Shotgun approach.
You should look, what event is called on click of Grid.

1 solution

Add one more condition which is gridMappings.Rows.Count>0
private void gridMappings_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            if (this.gridMappings.DataSource != null)
            {
                int lastRow =0;
                if(gridMappings.Rows.Count>0)
                lastRow this.gridMappings.Rows.Count - 1;
 
                for (int i = 0; i < this.gridMappings.Rows.Count; i++)
                {
                    if (this.gridMappings.Rows[i] != null)
                    {
                        this.gridMappings.Rows[i].Cells[2].Value = "Add";
                    }
                    else
                    {
                        this.gridMappings.Rows[i].Cells[2].Value = "Edit";
                    }
                    
                }
            }
        }
 
Share this answer
 
v2

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