Winform DataGridView添加数据后,数据自动删除的问题

最近碰到一个问题,在DataGridView里添加数据后,当失去行焦点时,数据会自动删除的问题

DataGridView数据来自DataTable

一直没有找到问题所在.

  /// <summary>

        /// 添加新行到DataGridView中

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void dgv_NewRowNeeded(object sender, DataGridViewRowEventArgs e)

        {

             if (dgvContact.Focused)

            {

                e.Row.Cells["ContactSex"].Value = "男";

                e.Row.Cells["ContactDuties"].Value = CommonHelp.GetTypeName(1);

                e.Row.Cells["ContactName"].Value = "请输入姓名";

                // e.Row.Cells["Contact_CustomerId"].Value = GetCustomerId;

            }

            else if (dgvWeb.Focused)

            {

                e.Row.Cells["WebServiceType"].Value = CommonHelp.GetTypeName(4);

                e.Row.Cells["WebService"].Value = CommonHelp.GetTypeName(2);

                e.Row.Cells["WebStatus"].Value = CommonHelp.GetTypeName(5);

                e.Row.Cells["WebPrice"].Value = 0;

                e.Row.Cells["CostPrice"].Value = 0;

                e.Row.Cells["WebStartDate"].Value = DateTime.Now.Date.ToString("yyyy-MM-dd");

                e.Row.Cells["WebEndDate"].Value = DateTime.Now.AddYears(1).ToString("yyyy-MM-dd");

                e.Row.Cells["WebAddress"].Value = "请输入地址";

             //   e.Row.Cells["Web_CustomerId"].Value = GetCustomerId;

            }

        }

经过一上午的排查终于找到原因,上面代码注释的地方

原来DataGridview添加行时,会根据绑定的数据的类型对DataGridView行进行验证,因为我在添加时没有对Contact_CustomerId和Web_CustomerId列进行 设置,所以他们默认值是Null,而绑定的数据类型是Int,所以验证没有通过

但数据还是会添加到绑定的DataTable中只是不会在DataGridView中并不会显示出来而已,.

原文地址:https://www.cnblogs.com/huangtailang/p/2182453.html