EKsumic's Blog

let today = new Beginning();

Click the left button to use the catalog.

QA

[C#] WinForm綁定的DataGridView顯示的表格的數據無法編輯或複製怎麽辦?

數據的綁定方式會影響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 13:35:35

* *