无法从Gridview – Windows窗体中将记录插入表中
我正在尝试从C#接口网格视图中将新记录插入到源表中….但是当我使用下面显示的buttonclick代码检索记录时…我在gridview中获取记录但没有插入新记录的选项(附加屏幕截图)..我可以从网格视图更新reocrds。
是否有任何选项或属性用于在gridview中启用插入选项?
Buttonclickcode:
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(); }
谢谢
使用DataGridView,DataTable和TableAdapter的CRUD操作
让用户使用DataGridView
添加,删除或编辑行:
- 将
AllowUserToAddRows
属性设置为true或在DataGridView Tasks中 ,选中Enable Adding - 将
AllowUserToDeleteRows
属性设置为true或在DataGridView Tasks中 ,选中Enable Deleting - 将
ReadOnly
属性设置为false或在DataGridView任务中 ,选中“ 启用编辑”
让用户使用SqlDataAdapter保存更改:
- 使用select语句和连接字符串创建
SqlDataAdapter
。 - 您应该为数据适配器使用有效的
InsertCommand
,DeleteCommand
和UpdateCommand
。 使用SqlCommandBuilder
创建有效命令。 - 使用数据适配器将数据加载到
DataTable
。 - 将数据表设置为
DataGridView
DataSource
- 通过将数据表传递给方法,在需要使用
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); }
注意
- 您不需要
ExecuteNonQuery
。 您只需要一个连接字符串和一个命令文本。 然后,您可以创建数据适配器。 然后你甚至不需要管理打开和关闭连接,数据适配器管理它。 - 使用
SELECT TOP 1 *
加载数据时,如果添加数据并保存,则下次加载数据时无法看到更新,因为只加载了一条记录。
代码正在使用ExecuteNonQuery
,它不会返回受影响的行,而不会返回查询返回的结果。
请改用ExecuteReader
。
var reader = cmd1.ExecuteReader(); DataTable dt = new DataTable(); dtLoad(reader);
是否有任何选项或属性用于在gridview中启用插入选项
dataGridView1.ReadOnly = false; dataGridView1.EditMode = DataGridViewEditMode.EditOnF2; //if you want to edit on F2.