【问题标题】:How to add a new row to the datagridview and edit it in C# winform?如何向 datagridview 添加新行并在 C# winform 中对其进行编辑?
【发布时间】:2017-08-07 06:56:09
【问题描述】:

我已将 datagridview 的数据源设置为数据集。我想向这个 datagridview 添加一个新行。这个新行应该是可编辑的,我需要将此数据保存到我的数据库中。我怎样才能做到这一点?

// 数据源已设置

dataGridView.DataSource = ds.Tables[0];

// 添加新行

 private void button_add_Click(object sender, EventArgs e)
 {
     DataTable dt = dataGridView.DataSource as DataTable;
     dt.Rows.Add();
     dataGridView.DataSource = dt;
 }

// 这会创建一个新行,但不可编辑。

附:我是 C# 初学者

编辑:谁能提供一个链接/示例,我可以在不使用任何表单的情况下直接从 datagridview 添加、编辑、删除?

【问题讨论】:

  • 你检查了吗-c-sharpcorner.com/UploadFile/1e050f/…。它涵盖了大部分的datagridview操作
  • @SouvikGhosh 这个例子有一个要填写的表格以供插入,但我想在我现有的 datagridview 中添加一行,向其中添加数据并保存它

标签: c# winforms datagridview


【解决方案1】:

我想你的问题是,你希望 DataGridView 的其余部分是只读的吗?不幸的是,AllowUserToAddRows 和 ReadOnly 这两个属性是矛盾的,如果 ReadOnly 为真,那么 AllowUserToAddRows 确实会给出一个新行,但是你不能编辑它。

因此,如果您真的想这样做,那么您需要有点创意。有不止一种方法,但这样的事情应该有效。将 AllowUserToAddRows 设置为 true,将 ReadOnly 设置为 false。添加私有字段:

private int addedRowIndex = -1;

接下来添加几个事件:

private void dataGridView1_UserAddedRow(object sender, DataGridViewRowEventArgs e)
{
    addedRowIndex = dataGridView1.NewRowIndex - 1;
}

private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
    {
        if (!dataGridView1.Rows[e.RowIndex].IsNewRow)
        {
            if (addedRowIndex != e.RowIndex)
            {
                e.Cancel = true;
            }
        }
    }
}

这将取消对旧行的所有更改。

但是请注意,我自己从来没有做过这样的事情。我有很多很多带有 DataGridViews 的表单,它们总是 ReadOnly true 和 AllowUserToAddRows false。要添加新记录,我提供了一个按钮,该按钮打开一个模式表单,允许用户输入新记录。然后将此记录保存到数据库并关闭表单,此时 DataGridView 会被刷新。我发现这使得在保存之前验证条目变得更加容易。不仅如此,为特定数据类型提供专门的控件要容易得多,日期就是一个很好的例子。我知道人们喜欢电子表格类型“外观”的便利性,但数据库应用程序应该将数据完整性放在首位。

【讨论】:

    【解决方案2】:
    private void button_add_Click(object sender, EventArgs e) {
        foreach (DataGridViewRow row in DataGridView1.Rows) {
            if (// condition for true) {
                row.Rows[row that should be editable].ReadOnly = true;
            } else if(// condition for false) {
                row.Rows[row that schould not be editable].ReadOnly = false;
            }
            var value = row.Cells[cellindex].Value;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-21
      • 1970-01-01
      相关资源
      最近更新 更多