[C#] WinForm綁定的DataGridView顯示的表格的數據無法編輯或複製怎麽辦?
Copyright Notice: This article is an original work licensed under the CC 4.0 BY-NC-ND license.
If you wish to repost this article, please include the original source link and this copyright notice.
Source link: https://v2know.com/article/27
數據的綁定方式會影響DataGridView顯示的數據是否可以編輯。
像
dataGridView1.DataSource = dataTable;
這種方式不要直接使用,
需要先使用
dataAdapter.Fill(dataTable);
例:
dataGridView1的這種綁定方式
private void LoadData()
{
string query = "{你的SELECT查詢文}";
using (SqlConnection connection = new SqlConnection(connString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(query, connection))
{
SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);
dataGridView1.DataSource = dataTable;
}
}
}
比:
using (var connection = new NpgsqlConnection(connString))
{
string query = @"{你的SELECT查詢文}";
connection.Open();
using (var command = new NpgsqlCommand(query, connection))
{
var reader = command.ExecuteReader();
var dataTable = new DataTable();
dataTable.Load(reader);
dataGridView2.DataSource = dataTable;
}
}
}
dataGridView2的這種方式要好。
微軟的DataAdapter默認給你寫了編輯的功能。
請用DataAdapter做數據,而不是直接source關聯dataTable.
This article was last edited at 2024-08-02 04:35:35