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)
要让用户添加、删除或编辑行DataGridView:
AllowUserToAddRows属性设置为 true 或在DataGridView Tasks 中,选中启用添加AllowUserToDeleteRows属性设置为 true 或在DataGridView Tasks 中,选中Enable DeletingReadOnly属性设置为 false 或在DataGridView Tasks 中,选中Enable Editing要让用户使用 SqlDataAdapter 保存更改:
SqlDataAdapter使用 select 语句和连接字符串创建一个。InsertCommand,DeleteCommand和UpdateCommand用于您的数据适配器。使用SqlCommandBuilder.DataTable将数据加载到使用数据适配器。DataSource的DataGridViewSqlDataAdapter.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 *,如果添加数据并保存,下次加载数据时将看不到更新,因为您只加载了一条记录。| 归档时间: |
|
| 查看次数: |
1469 次 |
| 最近记录: |