DataGridView单击新行会导致未处理的异常 [英] DataGridView Clicking on new Row causes unhandled exception

查看:116
本文介绍了DataGridView单击新行会导致未处理的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个绑定到BindingSource的表单上有一个DataGridView,它具有DataTable的DataSource

 

I已将DataTable的其中一列设置为AllowDBNull设置为false。当表单加载时,我使BindingSource添加一个新行。当您查看
DataGridView时,它有一个空行(bindingSource添加的行),然后是DataGridView NewRow。

如果我点击DataGridView NewRow我得到一个UnhandledException,说我的列不允许空值。这是正确的我的问题是我无法找到办法
来处理异常,无论我什么事都没有尝试解雇。


    public Form1()
    {
      InitializeComponent();

      DataTable dt = new DataTable();
      dt.Columns.Add("Col1", typeof(string));
      dt.Columns.Add("Col2", typeof(string));

      dt.Columns[0].AllowDBNull = false;

      BindingSource bs = new BindingSource();
      bs.DataSource = dt;
      dataGridView1.DataSource = bs;
      bs.AddNew();
    }

推荐答案

确定是一个错误。 column1中没有必需的值(因为您将column1(在索引0处)设置为NOT allow DBNull)。

Sure its an error. There is no required value in column1 (because you set column1 (at index 0) to NOT allow DBNull).

因此,如果插入新行,则必须在column1中提供值。在其他任何事情之前(实际上你要在dataSource中提供一个值 - 这是在dataTable中)。

So if insert a new row, you have to provide a value in column1. before anything else (actually you hav to provide a value in the dataSource - this is in dataTable).

解决方案:删除最后一行代码:bs.AddNew()方法!

Solution: Remove last line of code : bs.AddNew() method!

仅使用:


 table.Columns[0].AllowDBNull = false;
 dataGridView1.DataSource = new BindingSource(table, null);   
  


这篇关于DataGridView单击新行会导致未处理的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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