gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 09:47:30 26 4
gpt4 key购买 nike

我正在尝试从 C# 界面 GridView 将新记录插入到源表中....但是当我使用下面显示的 buttonclick 代码检索记录时...我在 gridview 中获取记录但没有插入新记录的选项(附有屏幕截图)..我可以从 GridView 更新 reocrds。

是否有任何选项或属性可以在 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();

}

Screenshot of the gridview where there is no option for insertion谢谢

最佳答案

使用 DataGridView、DataTable 和 DataAdapter 的 CRUD 操作

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

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

让用户使用 SqlDataAdapter 保存更改:

  1. 创建 SqlDataAdapter使用选择语句和连接字符串。
  2. 您应该有有效的 InsertCommand , DeleteCommandUpdateCommand为您的数据适配器。使用 SqlCommandBuilder 创建有效命令.
  3. 加载数据到 DataTable使用数据适配器。
  4. 设置数据表为DataGridViewDataSource
  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();
}

注意

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

关于c# - 使用 DataGridView、DataTable 和 DataAdapter 的 CRUD 操作 - 无法向 DataGridView 添加新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36274296/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com