c# – 无法从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添加,删除或编辑行: >将 让用户使用SqlDataAdapter保存更改: >使用select语句和连接字符串创建 码 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 *加载数据时,如果添加数据并保存,则下次加载数据时无法看到更新,因为您只加载了一条记录. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |