private void populateGridWithMessageCount() { DataTable dt = new DataTable(); dt.Columns.Add("MsgCount", typeof(int)); dt.Columns.Add("File Name", typeof(string)); int fileColumnIndex = Grid.Columns["File Name"].Index; SqlConnection conn = SystemMessage.InitSqlConnection(); SqlCommand command = new SqlCommand(); string sql = ""; foreach (DataGridViewRow row in Grid.Rows) { string fileName = row.Cells[fileColumnIndex].Value.ToString(); string filePath = txtPath.Text + "\\" + fileName; string fileNameWithPath = ""; if (!fileName.Contains("\\")) { fileNameWithPath = Regex.Split(txtPath.Text, @"\\").Last() + "/" + fileName; } fileNameWithPath = SystemMessage.ValidateFilename(fileNameWithPath); sql = "SELECT COUNT(*) FROM systemmessage WHERE FILENAME = '" + fileNameWithPath + "'"; command = new SqlCommand(sql, conn); string msgCount = command.ExecuteScalar().ToString(); dt.Rows.Add(msgCount, fileName); } Grid.DataSource = dt; Grid.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; }