How to select visible columns in Datagridview bound to DataTable

前端 未结 4 1694
栀梦
栀梦 2020-12-11 22:36

I have these fields on Customer DataTable: ID,title,Name,Addrs,email,Fax and this code to bind the DataGridView:

         


        
4条回答
  •  死守一世寂寞
    2020-12-11 23:25

    I know this post goes way back, but I had the same problem in C# and this is how I solved it which works really well.

    1 - Build a DataSet with your SQL query

         private void LoadDS()
         {
             // this method gets data from my database
             // DS is a DataSet in the properties of my form
             DS = LoadData();
         }
    

    2 - Get the DataView filtered the way you want

    For this I use the RowFilter property of the DataView. I created a GetFiltersToString() method that formats every filter control I have in a string that matches the RowFilter syntax (more information about the syntax here, and msdn definition of RowFilter here)

        public void RefreshDGV()
        { 
            // Get the corresponding dataview
            DV = new DataView(DS.Tables[0], rowFilter, "SORTINGCOLUMN Desc", DataViewRowState.CurrentRows);
            // Display it in a datagridview
            DGV.DataSource = DV;
        }
    

    I find that this solution allows user to change the filtering much more easily.

提交回复
热议问题