【问题标题】:How to add new row to datagridview only after specific cells of the row above are filled?只有在上面行的特定单元格被填充后,如何向datagridview添加新行?
【发布时间】:2011-02-26 11:05:34
【问题描述】:

我正在使用 C# (.NET 4.0) 开发桌面应用程序。我有一个 datagridview 填充自定义对象,通过自定义(它继承 BindingList)BindingList(添加排序功能)。我使用 cellValidating 事件来正确增加第一列 (ID) 并验证对其他单元格的输入。

问题是当我到达新行/最后一行并在一个单元格中输入一些内容(我什至可以在离开单元格之前删除所有输入)时,datagridview 会自动将此行添加到绑定列表并在下面创建一个新行.我希望仅在正确填充上面的行(上一个新行)时才添加最后一行/新行。

示例

ID     NAME      PRICE    ...

1      Beer       2.6

2      Cheese      3.3

_      _______     ____      <- empty row

现在,如果我单击(输入)新行 ID 将自动设置为 3,如果我将单击保留为“啤酒”单元格,则新行 ID 为空并且所有默认值都为空(这是它应该这样做的方式)工作)。 问题是,如果单击/输入新行并输入名称(即使我在离开单元格之前删除内容),则会在该行下方添加一个新行,这是新行。因此,这一行被添加到 BindingList 并且是不完整的,在正确填充所有必需的单元格(例如价格)之前不应添加它。

我不知道该怎么做。请帮帮我,我对 C# 很陌生。

感谢您的时间和回答。

【问题讨论】:

    标签: c# validation datagridview row


    【解决方案1】:

    您必须处理RowValidating事件并在检查特定条件(验证规则)后取消对该事件的处理。然后,当前正在输入的行将不会提交到 DataGridView 并且不会添加新行。

    例如:

    if (dgv[0, e.RowIndex].Value == DBNull.Value)
    {
        dgv.Rows[e.RowIndex].ErrorText = "You must enter a value for this field!";
    
        // Tell the DataGridView not to accept this row
        e.Cancel = true;
    }
    

    【讨论】:

      【解决方案2】:

      如果您正在开发 Windows 应用程序并且有文本框来获取用户的输入以更新到 DataGridView,您可以在 C# 本身中执行此操作,请考虑以下事项:

      if(txtNAME.Text.Trim()!=String.Empty&&txtPRICE.Text.Trim()!=String.Empty)
      {
        MessageBox.Show("Invalid type of input","Alert", MessageBoxButtons.OK, MessageBoxIcon.Error);
      }
      
      else
      {
        SqlConnection _sqlconnectionOne=new SqlConnection(*DatabaseConnectionString*);
      
        SqlCommand _sqlcommandOne=new SqlCommand();
      
        _sqlcommandOne.CommandType=CommandType.Text;
        _sqlcommandOne.CommandText="*INSERTStatement*";
        _sqlcommandOne.Connection=_sqlconnectionOne;
        _sqlcommandOne.ExecuteNonQuery();
      
        SqlConnection _sqlconnectionSecond=new SqlConnection(*DatabaseConnectionString*);
      
        SqlCommand _sqlcommandSecond=new SqlCommand();
      
        _sqlcommandSecond.CommandType=CommandType.Text;
        _sqlcommandSecond.CommandText="*SELECT*Statement*";
        _sqlcommandSecond.Connection=_sqlconnectionSecond;
      
        SqlDataAdapter _sqldataadapter=new SqlDataAdapter(_sqlcommandSecond);
      
        DataTable _datatable=new DataTable();
      
        _sqldataadapter.fill(_datatable);
        *DataGridViewName*.DataSource=_datatable;
      }
      

      或者您可以为文本框使用离开事件,但有时它会变得有点麻烦。 欢迎提出建议!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-18
        • 1970-01-01
        • 2012-03-03
        • 2019-02-25
        • 2023-03-22
        • 1970-01-01
        • 2015-10-02
        • 2017-08-30
        相关资源
        最近更新 更多