我正在尝试从C#接口网格视图中将新记录插入到源表中…. 但是当我使用下面显示的buttonclick代码检索记录时…我在gridview中获取记录但没有插入新记录的选项(附加屏幕截图)..我可以从网
但是当我使用下面显示的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添加,删除或编辑行:
>将AllowUserToAddRows属性设置为true或在DataGridView任务中,选中“启用添加”
>将AllowUserToDeleteRows属性设置为true或在DataGridView任务中,选中启用删除
>将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 *加载数据时,如果添加数据并保存,则下次加载数据时无法看到更新,因为您只加载了一条记录.
