DataGridView RowsAdded Index -1没有值? [英] DataGridView RowsAdded Index -1 does not have a value ?

查看:67
本文介绍了DataGridView RowsAdded Index -1没有值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hi


在窗口应用程序中,我将DataGridViewDataSource绑定到对象列表。 DGV包含3列。前两列是Simple DataGridViewTextBoxColumn&在第3列中是DataGridViewButtonColumn的类型。它运行良好但我想在将行添加到gridview时根据Source的某个值更改Button的名称(如Add / Edit)。所以我使用RowsAdded事件。代码是

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

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";
                    }
                    
                }
            }
        }





工作完美但是在将行添加到gridview后,当我单击网格上的任何位置时,我收到错误索引-1没有值。在Program.cs文件中。



请帮助!

谢谢



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

推荐答案

再添加一个条件,即gridMappings.Rows.Count> 0

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";
                    }
                    
                }
            }
        }


这篇关于DataGridView RowsAdded Index -1没有值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆