使用 DataGridView、DataTable 和 DataAdapter 的 CRUD 操作 - 无法向 DataGridView 添加新行

Gow*_*thy 3 .net c# datagridview winforms

我正在尝试从 C# 界面网格视图向源表中插入新记录......但是当我使用下面显示的按钮点击代码检索记录时......我在网格视图中获取记录但没有插入新记录的选项(附上屏幕截图).. 我可以从网格视图更新记录。

是否有任何选项或属性可以在 gridview 中启用插入选项?

按钮点击代码:

private void RetrieveRules_button_Click(object sender, EventArgs e)
{
    this.dataGridView.DataSource = null;
    this.dataGridView.Rows.Clear();


    SqlCommand cmd1 = con.CreateCommand();
    cmd1.CommandType = CommandType.Text;
    cmd1.CommandText = @" Select TOP 1 * FROM " + schemaName + "[ERSBusinessLogic] ORDER BY ERSBusinessLogic_ID     DESC";
    con.Open();
    cmd1.ExecuteNonQuery();
    DataTable dt = new DataTable();
    SqlDataAdapter DA = new SqlDataAdapter(cmd1);
    DA.Fill(dt);
    dataGridView.DataSource = dt;
    con.Close();

}
Run Code Online (Sandbox Code Playgroud)

没有插入选项的 gridview 的屏幕截图 谢谢

Rez*_*aei 5

使用 DataGridView、DataTable 和 DataAdapter 的 CRUD 操作

要让用户添加、删除或编辑行DataGridView

  1. AllowUserToAddRows属性设置为 true 或在DataGridView Tasks 中,选中启用添加
  2. AllowUserToDeleteRows属性设置为 true 或在DataGridView Tasks 中,选中Enable Deleting
  3. ReadOnly属性设置为 false 或在DataGridView Tasks 中,选中Enable Editing

要让用户使用 SqlDataAdapter 保存更改:

  1. SqlDataAdapter使用 select 语句和连接字符串创建一个。
  2. 您应该有有效的InsertCommand,DeleteCommandUpdateCommand用于您的数据适配器。使用SqlCommandBuilder.
  3. DataTable将数据加载到使用数据适配器。
  4. 组数据表作为DataSourceDataGridView
  5. 在需要使用时SqlDataAdapter.Update通过将数据表传递给方法来保存更改。

代码

DataTable table;
SqlDataAdapter adapter;
private void Form1_Load(object sender, EventArgs e)
{
    //Create adapter
    var connection = @"your connection string";
    var command = "SELECT * FROM Table1";
    adapter = new SqlDataAdapter(command, connection);

    //Create Insert, Update and Delete commands
    var builder = new SqlCommandBuilder(adapter);

    //Load data
    table = new DataTable();
    adapter.Fill(table);

    //Bind the grid to data
    this.dataGridView1.DataSource = table;

    //Enable add, delete and edit
    this.dataGridView1.AllowUserToAddRows = true;
    this.dataGridView1.AllowUserToDeleteRows = true;
    this.dataGridView1.ReadOnly = false;
}

private void saveButton_Click(object sender, EventArgs e)
{
    //Save Data
    adapter.Update(table);
}

private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
    adapter.Dispose();
}
Run Code Online (Sandbox Code Playgroud)

笔记

  • 你不需要那个ExecuteNonQuery。您只需要一个连接字符串和一个命令文本。然后您可以创建一个数据适配器。然后你甚至不需要管理打开和关闭连接,数据适配器管理它。
  • 使用 加载数据时SELECT TOP 1 *,如果添加数据并保存,下次加载数据时将看不到更新,因为您只加载了一条记录。