none
Set Default View Of DataGridView To Variable RRS feed

  • Question

  • I am attempting to use a foreach loop to filter a datagridview and export each unique value to a csv file.

    I have the following syntax but it never changes the default view of the datagridview, all data is always shown.  Where did I err?

    	//Creating a DataTable of unique stores
    	Form1.dtStoreNames = Form1.allemps.DefaultView.ToTable(true, "Employee");
    
    	foreach(DataRow row in Form1.dtStoreNames.Rows)
    	{
    		//Binding the newly created datatable to the datagrid
    		dataGridView1.DataSource = Form1.allemps;
    		dataGridView1.AutoResizeColumns();
    		((DataTable)dataGridView1.DataSource).DefaultView.RowFilter = "Employee = " + row; 
    		
    		
    		//Exporting To CSV
    		ExportToCSV();
    	}
    

    Saturday, December 16, 2017 9:26 AM

Answers

  • Hello,

    Try creating a variable of the DefaultView, apply the RowFilter then create a variable that converts the DefaultView to a Table. This is slightly different than how you are currently coding as in the current method shown as you learned the results are not what you expected. To see what I suggested work try the code sample found on the following page.

    The key lines from the code sample, look past the fact there is no DataGridView but we are still dealing with a DataTable and DataView which we of course can get at like you are by casting the DataGridView's DataSource yet as mentioned above we first need to have an instance of the DataView and not simply apply the RowFilter.

    DataView view = new DataView(table);
    view.RowFilter = "QuantityInStock > 15";
    PrintTableOrView(view, "Current Values in View");
    
    DataTable newTable = view.ToTable();
    PrintTableOrView(newTable, "Table created from filtered DataView");
    


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    • Marked as answer by IndigoMontoya Saturday, December 16, 2017 3:49 PM
    Saturday, December 16, 2017 11:05 AM
    Moderator