Luke Hottinger
Luke Hottinger

Reputation: 57

Parsing a DataGridView - C#

I'm trying to write an application in C# that will analyze two different data sets and try to find matches between them. My question is, what would be the best way for me to go through the data rows and extract data from them?

I would need to extract entire rows of data, with multiple columns, and analyze them for similarities.

Would the best way be to put the row into a string and parse it?

EDIT: This is the code I'm using to put the data in a DataGridView it's from an excel spreadsheet:

try
                {
                    OleDbConnectionStringBuilder connStringBuilder = new OleDbConnectionStringBuilder();
                    connStringBuilder.DataSource = file;
                    connStringBuilder.Provider = "Microsoft.Jet.OLEDB.4.0";
                    connStringBuilder.Add("Extended Properties", "Excel 8.0;HDR=NO;IMEX1");

                    DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");

                    DbDataAdapter adapter = factory.CreateDataAdapter();

                    DbCommand selectCommand = factory.CreateCommand();
                    selectCommand.CommandText = "SELECT * FROM [All Carpets to Excel$]";

                    DbConnection connection = factory.CreateConnection();
                    connection.ConnectionString = connStringBuilder.ConnectionString;

                    selectCommand.Connection = connection;

                    adapter.SelectCommand = selectCommand;

                    data = new DataSet();

                    adapter.Fill(data);

                    dataGridView1.DataSource = data.Tables[0].DefaultView;



                }
                catch (IOException)
                {

                }

I haven't tried any code to analyze and compare just yet, but I first need to know what the best way to access the data and format it.

Thanks!

Upvotes: 0

Views: 2349

Answers (1)

Chris Knight
Chris Knight

Reputation: 1486

I like to work with List objects, and use LINQ to run compares and run queries. Here is an example of taking a DataSet (your 'data' property from your example) and getting a DataTable from it. Then I loop through the rows & columns and populate a List. The last line is just an example of using a LINQ query on the new List.

DataSet grid = new DataSet();
            DataTable table = grid.Tables[0];

            List<string> tableData = new List<string>();
            foreach (DataRow row in table.Rows)
            {
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    tableData.Add(row[i].ToString());
                }
            }

            tableData.Where(x => x == "TestValue");

Let me know if there are questions on this.

Upvotes: 1

Related Questions