两种方法:
(1)数据源使用DataTable
/// <summary> /// 绑定DataGridView /// </summary> private void BindDataGridView() { //绑定DataGridView的数据 string pro_json = client.GetStringAsync($"http://localhost:52972/api/Procuct?ProName={tbKeyword.Text}&ClassID={treeView1.SelectedNode.Name}").Result; //反序列化 DataTable ProList = JsonConvert.DeserializeObject<DataTable>(pro_json); //不自动生成 dataGridView1.AutoGenerateColumns = false; //设置数据源 dataGridView1.DataSource = ProList; }
(2)数据源使用BindingList,因为BindingList实现了IBindingList接口;
相关代码如下:
/// <summary> /// 绑定DataGridView /// </summary> private void BindDataGridView() { //绑定DataGridView的数据 string pro_json = client.GetStringAsync($"http://localhost:52972/api/Procuct?ProName={tbKeyword.Text}&ClassID={treeView1.SelectedNode.Name}").Result; //反序列化 BindingList<ProductModel> ProList = JsonConvert.DeserializeObject<BindingList<ProductModel>>(pro_json); //不自动生成 dataGridView1.AutoGenerateColumns = false; //设置数据源 dataGridView1.DataSource = ProList; }